|
这里用到了两个文件,一个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 bean文件源代码
//导入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;
}
}
jsp技术:jsp文件操作之读取篇,转载需保留来源!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。