北方站长站
客服热线:0632-5117766

jsp文件操作之读取篇

[2005-12-10 10:44:12] 作者:北方站长站 来源:不详      

Tags:读取 操作 文件 public path new // String file currentRecord

  

  文件操作是网站编程的重要内容之一,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;
}
}


 

 

News

 

info

 

down

出售手机裁听器,手机跟踪定位系统    企业网站,网城,购物网,都市导购,校园网    网上书店系统    上海电信机房服务器托管,双线主机托管    美女图片馆    15G 高清晰图片资源 无水印    室内装潢材料新产品杰威尔艺术漆    收一万ip的美女图片    大量收购个人网址导航网站    出售网址站PR=4alexa=119,764    

下一篇链接:jsp文件操作之追加篇

上一篇链接:jsp计数器制作手册

评论】 【打印】 【加入收藏】 【关闭→论坛 →博客 →数据中心

 共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面