jsp文件操作之讀取篇

2022-06-12發(fā)布者:ylm大?。?/span> 下載:0

文件大小:

軟件介紹

這里用到了兩個文件,一個jsp文件一個javabean文件,通過jsp中調(diào)用javabean可以輕松讀取文本文件,注意請放置一個文本文件afile.txt到web根目錄的test目錄下,javabean文件編譯后將class文件放到對應(yīng)的class目錄下(tomcat環(huán)境)。
Read.jsp

<html>
<head>
<title>讀取一個文件</title>
</head>
<body bgcolor="#000000">
<%--調(diào)用javabean --%>
<jsp:useBean id="reader" class="DelimitedDataFile" scope="request">
<jsp:setPRoperty name="reader" property="path" value="/test/afile.txt" />
</jsp:useBean>

<h3>文件內(nèi)容:</h3>

<p>

<% int count = 0; %>
<% while (reader.nextRecord() != -1) { %>
<% count++; %>
<b>第<% out.print(count); %>行:</b>
<% out.print(reader.returnRecord()); %><br>    
<% } %>
</p>
</body>
</html>


//DelimitedDataFile.java bean文件源代碼
//導(dǎo)入java包
import java.io.*;
import java.util.StringTokenizer;

public class DelimitedDataFile
{

private String currentRecord = null;
private BufferedReader file;
private String path;
private StringTokenizer token;
//創(chuàng)建文件對象
public DelimitedDataFile()
{
     file = new BufferedReader(new InputStreamReader(System.in),1);
}
public DelimitedDataFile(String filePath) throws FileNotFoundException
{
    
     path = filePath;
     file = new BufferedReader(new FileReader(path));
}
     //設(shè)置文件路徑
     public void setPath(String filePath)
        {
            
            path = filePath;
try {
file = new BufferedReader(new
FileReader(path));
} catch (FileNotFoundException e) {
            System.out.println("file not found");
            }
    
        }
//得到文件路徑
     public String getPath() {
        return path;
}
//關(guān)閉文件
public void fileClose() throws IOException
{
    
     file.close();
}
//讀取下一行記錄,若沒有則返回-1
public int nextRecord()
{
    
    
     int returnInt = -1;
     try
     {
     currentRecord = file.readLine();
     }
    
     catch (IOException e)
     {
     System.out.println("readLine problem, terminating.");
     }
    
     if (currentRecord == null)
     returnInt = -1;
     else
     {
     token = new StringTokenizer(currentRecord);
     returnInt = token.countTokens();
     }
     return returnInt;
}

    //以字符串的形式返回整個記錄
public String returnRecord()
{

return currentRecord;
}
}

發(fā)表評論(共0條評論)
請自覺遵守互聯(lián)網(wǎng)相關(guān)政策法規(guī),評論內(nèi)容只代表網(wǎng)友觀點,發(fā)表審核后顯示!

版權(quán)聲明:

1 本站所有資源(含游戲)均是軟件作者、開發(fā)商投稿,任何涉及商業(yè)盈利目的均不得使用,否則產(chǎn)生的一切后果將由您自己承擔(dān)!

2 本站將不對任何資源負(fù)法律責(zé)任,所有資源請在下載后24小時內(nèi)刪除。

3 若有關(guān)在線投稿、無法下載等問題,請與本站客服人員聯(lián)系。

4 如侵犯了您的版權(quán)、商標(biāo)等,請立刻聯(lián)系我們并具體說明情況后,本站將盡快處理刪除,聯(lián)系QQ:2499894784

返回頂部