17站长网

17站长网 首页 编程 JSP编程 查看内容

jsp文件操作之读取篇

2022-10-27 18:45| 查看: 1896 |来源: 互联网

文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看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;
}
}

tag标签:jsp asp jsp文件
本文最后更新于 2022-10-27 18:45,某些文章具有时效性,若有错误或已失效,请在网站留言或联系站长:17tui@17tui.com
·END·
站长网微信号:w17tui,关注站长、创业、关注互联网人 - 互联网创业者营销服务中心

免责声明:本站部分文章和图片均来自用户投稿和网络收集,旨在传播知识,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系我们及时修正或删除。谢谢!

下一篇:JSP动作上一篇:jsp文件操作之追加篇

17站长网微信二维码

始终以前瞻性的眼光聚焦站长、创业、互联网等领域,为您提供最新最全的互联网资讯,帮助站长转型升级,为互联网创业者提供更加优质的创业信息和品牌营销服务,与站长一起进步!让互联网创业者不再孤独!

扫一扫,关注站长网微信

大家都在看

    热门排行

      最近更新

        返回顶部