文件操作是网站编程的重要内容之一,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; } }
申明:本教程内容由威凡网编辑整理并提供IT程序员分享学习,如文中有侵权行为,请与站长联系(QQ:254677821)!
|