首页产品库评测行情新闻|手机数码笔记本台式机DIY硬件数字家庭数码相机办公外设|软件下载游戏开发|社区

更多

数码相机
MP4
LCD
机箱
音箱

天极网 > 软件频道>在JSP中操作文件

在JSP中操作文件

2002-04-23 17:37作者:出处:Yesky责任编辑:

  综述:无论是用JavaServer Page(JSP)技术,还是ASP、PHP技术实现的网站,都可能有计数器、投票等功能,这些功能的实现离不开对文件的操作。由此可见,文件操作对网站的建设来说,有着很重要的作用。
  本章首先介绍了JSP中文件的基本操作,包括读取操作、写入操作以及追加操作,然后在此基础上,通过实例,说明如何通过这三种基本操作,来实现计数器、投票等复杂功能。
JSP对文件的基本操作有哪些?

  读取操作

  读取操作是文件操作的基本功能之一,在计数器、投票统计中有着广泛的应用。那么,该操作在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
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;
}
}
共6页。 1 2 3 4 5 6 :

关注此文的读者还看过:

返回软件频道首页

共6页。 123456下一页

软件频道最新更新

热点推荐

天极服务|关于我们|About us|网站律师|RSS订阅|友情合作|加入我们|天极动态|网站地图|意见反馈|MSN/QQ上看天极
Copyright (C) 1999-2012 Yesky.com, All Rights Reserved 版权所有 天极网络