2000-11-28· coolknight·yesky
文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看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 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文件操作之写入篇>>。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器