top
Loading...
在JSP中操作文件
綜述:無論是用JavaServer Page(JSP)技術,還是ASP、PHP技術實現的網站,都可能有計數器、投票等功能,這些功能的實現離不開對文件的操作。由此可見,文件操作對網站的建設來說,有著很重要的作用。
本章首先介紹了JSP中文件的基本操作,包括讀取操作、寫入操作以及追加操作,然后在此基礎上,通過實例,說明如何通過這三種基本操作,來實現計數器、投票等復雜功能。
JSP對文件的基本操作有哪些?

讀取操作

讀取操作是文件操作的基本功能之一,在計數器、投票統計中有著廣泛的應用。那么,該操作在JSP中是如何實現的呢?請看下面的例子。

本例用到了兩個文件,一個jsp文件,一個Javabean文件。通過jsp中調用Javabean可以輕松讀取文本文件,注意請放置一個文本文件afile.txt到web根目錄的test目錄下,Javabean文件編譯后將class文件放到對應的class目錄下(tomcat環境)。

Read.jsp

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

<h3>文件內容:</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
import Java.io.*;
import Java.util.StringTokenizer;

public class DelimitedDataFile
{
private String currentRecord = null;
private BufferedReader file;
private String path;
private StringTokenizer token;

//創建文件對象
public DelimitedDataFile()
{
file = new BufferedReader(new InputStreamReader(System.in),1);
}

public DelimitedDataFile(String filePath) throws FileNotFoundException
{
path = filePath;
file = new BufferedReader(new FileReader(path));
}

//設置文件路徑
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;
}

//關閉文件
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;
}
}
作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗