您当前的位置: 首页 > 网站编程 > PHP教程 > JSP文件操作之读取篇

JSP文件操作之读取篇

作者:guanchaofeng 来源:不详 发布时间: 2008-10-05 10:24 点击:
文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看jsp中是如何实现的。 这里用到了两个文件,一个jsp文件一个javabean文件,通过jsp中调用javabean可以轻松读取文本文件,注意请放置一个文本文件afile.txt到web根目录的test

JSP文件操作之读取篇

    文件操作是网站编程的重要内容之一,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文件操作之读取篇"由远航站长收集整理而来,仅供大家学习与参考使用。更多网站制作教程尽在远航站长站。
顶一下
(0)
0%
踩一下
(0)
0%
[点击 次] [返回上一页] [打印]
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 密码: 验证码:
关于本站 - 联系我们 - 网站声明 - 友情连接- 网站地图 - 站点地图 - 返回顶部
Copyright © 2007-2013 www.yhzhan.com(远航站长). All Rights Reserved .
远航站长:为中小站长提供最佳的学习与交流平台,提供网页制作与网站编程等各类网站制作教程.
官方QQ:445490277 网站群:26680406 网站备案号:豫ICP备07500620号-4