在JSP中操作文件


综述:无论是用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;
}
}

一、前言

  该例子涉及到文件的读写和jpg图片的自动生成。利用jsp+servlet的技术,jsp调用servlet生成图片。

  二、首文件index.jsp如下

<%@ page contentType="text/html;charSet=gb2312"%>
<%
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",0);
%>
<%!
//getQuestion(String)函数用来获得文本文件中的问题
public String[] getQuestion(String s)
{
String[] strQ = new String[4];
String strTemp = null;
int i;
Java.io.RandomAccessFile rf = null;
try {
rf = new Java.io.RandomAccessFile(s,"r");
} catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
for(i=0;i<4;i++)
{
try {
strTemp = rf.readLine();
} catch(Exception e) {
strTemp = "None Question";
}
if(strTemp==null)strTemp = "None Question";
strQ = strTemp;
}
return strQ;
}
%>
<%
String s = null;
String[] question = new String[4];
s = request.getRealPath("question.txt");
question = getQuestion(s);
%>

<html>
<head>
<title></title>
<link href="css.css" rel="StyleSheet" type="text/css"></link>
</head>
<body>
<table width="180" border="1" bordercolor="#999999">
<tr>
<td align=center>冰帆调查</td>
</tr>
<form name=frm method=post action=write.jsp>
<tr>
<td>
<%
String ss = null;
for (int i=0;i<4;i++)
{
ss = "<input type=\"radio\" name=\"choice\" value=" + I + ">" + (char)('A'+i) + "、" + question[i]+"<br>";
out.println(ss);
}
%>
</td>
</tr>
<tr>
<td align=center><input type=submit value="我 投 一 票"></td>
</tr>
<tr>
<td align=center><img src="/vote/servlet/VoteImage" width=150 height=100> </td>
</tr>
</form>
</table>
</body>
</html>

三、写文件write.jsp



<%!
public int[] getNumber(String s)
{
int[] mCount = new int[4];
String strTemp = null;
int i;
Java.io.RandomAccessFile rf = null;
try {
rf = new Java.io.RandomAccessFile(s,"r");
} catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
for(i=0;i<4;i++)
{
try {
strTemp = rf.readLine();
} catch(Exception e) {
strTemp = "0";
}
if(strTemp==null) strTemp = "0";
mCount[i] = new Integer(strTemp).intValue();
}
return mCount;
}

public void setNumber(String s,int[] x)
{
try {
Java.io.PrintWriter pw = new Java.io.PrintWriter(new Java.io.FileOutputStream(s));
for (int i=0;i<4;i++)
{
pw.println(x[i]+"");
}
pw.close();
} catch(Exception e) {
System.out.println("Write file error:"+e.getMessage());
}
}
%>

<%
String tmp = null;
int choice = -1;
int[] count = new int[4];
tmp = request.getParameter("choice");
if (tmp==null){
}
else
{
choice = new Integer(tmp).intValue();
}
String s = request.getRealPath("count.txt");
if (choice>=0)
{
count = getNumber(s);
count[choice]++;
setNumber(s,count);
}
response.sendRedirect("index.jsp");
%>

四、servlet原代码:VoteImage.Java :



import Java.io.*;
import Java.util.*;
import com.sun.image.codec.jpeg.*;
import Javax.servlet.*;
import Javax.servlet.http.*;
import Java.awt.*;
import Java.awt.geom.*;
import Java.awt.image.*;
public class VoteImage extends HttpServlet
{
private String strFile = null;
private Color color[]={Color.red,Color.black,Color.orange,Color.green};
private int baseAng = 30;

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
strFile = request.getRealPath("count.txt");
float[][] xy = new float[4][2];
xy = getNumAndPercent(strFile);
int[] ang = new int[4];
ang[0] = (int)(xy[0][1]*360);
ang[1] = (int)(xy[1][1]*360);
ang[2] = (int)(xy[2][1]*360);
ang[3] = 360-ang[0]-ang[1]-ang[2];

response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",0);
response.setContentType("image/jpeg");
ServletOutputStream out=response.getOutputStream();
BufferedImage image = new BufferedImage ( 150 , 100 , BufferedImage. TYPE_INT_RGB);
Graphics2D g = (Graphics2D)image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.white);
g.fillRect(0,0,150,100);
AffineTransform at = null;
Arc2D arc = null;
int fromAng = baseAng;

at = AffineTransform.getRotateInstance((-20*Java.lang.Math.PI)/180,45,37);
g.setTransform(at);
int r =6;
int dx = (int) ( r * Java.lang.Math.cos ( ( baseAng + ang[0] ) / 2.0 * Java.lang.Math.PI / 180 ) );
int dy = ( int ) ( r * Java.lang.Math.sin (( baseAng + ang[0] ) / 2.0 * Java.lang.Math.PI / 180 ) );
arc = new Arc2D.Double(10+dx,24-dy,80,50,fromAng,ang[0],Arc2D.PIE);
g.setColor(color[0]);
g.fill(arc);
fromAng+=ang[0];
for (int i=1;i<4;i++)
{
g.setColor(color[i]);
arc = new Arc2D.Double(10,24,80,50,fromAng,ang[i],Arc2D.PIE);
g.fill(arc);
fromAng+=ang[i];
if (fromAng>360)
{
fromAng-=360;
}
}
at = AffineTransform.getRotateInstance(0,arc.getCenterX(),arc.getCenterY());
g.setTransform(at);

for (int i=0;i<4;i++)
{
g.setColor(color[i]);
g.fillRect(100,15*i+20,10,10);
g.drawString((char)('A'+i)+"",120,15*i+20+8);
}
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
doGet(request,response);
}

public synchronized float[][] getNumAndPercent(String sFileName)
{
float xx[][] = new float[4][2];
int totalNum = 0 ;
String strTemp = null;
int i = 0;
Java.io.RandomAccessFile rf = null;
try
{
rf = new Java.io.RandomAccessFile (sFileName,"r");
} catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
for (i=0;i<4;i++)
{
int m=0;
try {
strTemp = rf.readLine();
} catch (Exception e){
strTemp = "0";
}
if (strTemp == null) strTemp = "0";
m = new Integer(strTemp).intValue();
xx[i][0]=m;
totalNum += m;
}
if (totalNum==0) totalNum=1;
for ( i=0;i<4;i++)
{
xx[i][1] = xx[i][0]/totalNum;
}
return xx;
}
}

  五、在index.jsp目录下建立question.txt和count.txt文件分别用来保存投票的问题和投票的数量,用户投票后,就修改count.txt的值。



question.txt:
Yes,I think so!
No,I dont think so!
Sorry,I dont know the answer!

count.txt:
12
9
5
9

写入操作

  本例使用两个文件,一个jsp文件,一个Javabean文件。通过jsp中调用Javabean可以轻松读取文本文件,注意请放置一个文本文件afile.txt到web根目录的test目录下,Javabean文件编译后将class文件放到对应的class目录下(tomcat环境)。



WriteOver.jsp
<html>
<head>
<title>Write over a file</title>
</head>
<body bgcolor="#000000">
<jsp:useBean id="writer" class="WriteOver" scope="request">
<jsp:setProperty name="writer" property="path" value="/path/to/afile.txt" />
<jsp:setProperty name="writer" property="something" value="Something already set as a property in WriteOver" />
</jsp:useBean>
<h3>Write to the file</h3>
<p>
<%
writer.setSomething("Something to write to the file");
out.print(writer.getSomething());
out.print(writer.writeSomething());
%>
</p>
</body>
</html>

WriteOver.Java
import Java.io.*;
public class WriteOver
{
private String path;
private String something;

// WriteOver构造器,用于初始化参数
public WriteOver() {
path = null;
something = "Default message";
}

//设置文件路径
public void setPath(String apath) {
path = apath;
}

//获取路径参数
public String getPath() {
return path;
}

//获取something参数值
public void setSomething(String asomething) {
something = asomething;
}

//设置something参数
public String getSomething() {
return something;
}

//将something参数的值写入paht指定的文件中
public String writeSomething()
{
try {
     File f = new File(path);
     PrintWriter out = new PrintWriter(new FileWriter(f));
     out.print(this.getSomething() + "\n");
     out.close();
return "Alles ist Gut.";
} catch (IOException e) {
     return e.toString();
}    
}
}

追加操作

  如何用jsp将数据追加到一个文件中呢?继续下面的例子吧。



writeAppend.jsp
<html>
<head>
<title>Append a file</title>
</head>
<body bgcolor="#000000">
<jsp:useBean id="writer" class="WriteAppend" scope="request">
<jsp:setProperty name="writer" property="path" value="/path/to/afile.txt" />
<jsp:setProperty name="writer" property="something" value="Something already set as a property in WriteAppend" />
</jsp:useBean>
<h3>Write to the file</h3>
<p>
<%
writer.setSomething("Something to write to the file");
out.print(writer.getSomething());
out.print(writer.writeSomething());
%>
</p>
</body>
</html>

WriteAppend.Java
import Java.io.*;
public class WriteAppend
{
private String path;
private String something;

// WriteAppend构造器,用于初始化参数
public WriteAppend() {
path = null;
something = "Default message";
}

//设置path参数
public void setPath(String apath) {
path = apath;
}

//获取path参数值
public String getPath() {
return path;
}

//设置参数something
public void setSomething(String asomething) {
something = asomething;
}

//获取something参数
public String getSomething() {
return something;
}

//追加操作
public String writeSomething()
{
try {
     FileWriter theFile = new FileWriter(path,true);
PrintWriter out = new PrintWriter(theFile);
     out.print(something + "\n");
     out.close();
    theFile.close();
     return "Das war sehr gut!";
} catch (IOException e) {
     return e.toString();
}    
}
}

  注意源程序中的加粗行,它是实现追加操作的关键。在创建FileWriter对象时,使用了FileWriter类的FileWriter(String filename , boolean append)构造函数,其中append参数用于决定对将写入的数据是否进行追加操作。

如何利用文件操作实现简单的计数器?

  计数器是一般网站必备的东东,别小看它了,每当站长看着小小计数器上的数字飞速增长的时候,感觉实在是好极了。以前我们用cgi、asp来写计数器,这方面的文章很多了,在这里,我们将会采用jsp技术演示如何做一个计数器。

  其中用到了两个文件,test.jsp文件用于在浏览器中运行,counter.Java是后台的一个小Java bean程序,用来读计数器的值和写入计数器的值。而对于计数器的保存,我们采用了一个文本文件lyfcount.txt。
下面是详细的程序代码(test.jsp放到web目录下,counter.Java放到class目录):



//test.jsp文件
<%@ page contentType="text/html;charset=gb2312"%>
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<META NAME="GENERATOR" CONTENT="Oracle JDeveloper">
<TITLE>计数器演示程序</TITLE>
</HEAD>
<BODY>
<!--创建并调用bean(counter)-->
<jsp:useBean id="counter" class="counter" scope="request">
</jsp:useBean>
<%
//调用counter对象的ReadFile方法来读取文件lyfcount.txt中的计数
String cont=counter.ReadFile("/lyfcount.txt");
//调用counter对象的ReadFile方法来将计数器加一后写入到文件lyfcount.txt中
counter.WriteFile("/lyfcount.txt",cont);
%>
您是第<font color="red"><%=cont%></font>位访问者
</BODY>
</HTML>

//counter.Java 读写文件的一个bean
import Java.io.*;
public class counter extends Object
{
private String currentRecord = null;//保存文本的变量
private BufferedReader file; //BufferedReader对象,用于读取文件数据
private String path;//文件完整路径名
public counter()
{
}
//ReadFile方法用来读取文件filePath中的数据,并返回这个数据
public String ReadFile(String filePath) throws FileNotFoundException
{
path = filePath;
//创建新的BufferedReader对象
file = new BufferedReader(new FileReader(path );
String returnStr =null;
try{
//读取一行数据并保存到currentRecord变量中
currentRecord = file.readLine();
}catch (IOException e)
{
//错误处理
System.out.println("读取数据错误.");
}
if (currentRecord == null)
//如果文件为空
returnStr = "没有任何记录";
else
{
//文件不为空
returnStr =currentRecord;
}
//返回读取文件的数据
return returnStr;
}

//WriteFile方法用来将数据counter+1后写入到文本文件filePath中
//以实现计数增长的功能
public void WriteFile(String filePath,String counter) throws FileNotFoundException
{
path = filePath;
//将counter转换为int类型并加一
int Writestr = Integer.parseInt(counter)+1;
try {
//创建PrintWriter对象,用于写入数据到文件中
PrintWriter pw = new PrintWriter(new FileOutputStream(filePath));
//用文本格式打印整数Writestr
pw.println(Writestr);
//清除PrintWriter对象
pw.close();
} catch(IOException e)
{
//错误处理
System.out.println("写入文件错误"+e.getMessage());
}
}
}

  到这里,程序写完了,将counter.Java编译为counter.class,同样放在对应的class目录下,在根目录下建立一个lyfcount.txt文件,文件内容就一个数字0,直接在浏览器中敲入地址就可以看到计数器了,刷新浏览器会看到不断变幻的数字。
  如果运行时候提示找不到文件,请将上面test.jsp中的readfile那一句注释后运行一次则lyfcount.txt文件自动建立,然后就可以正常运行。
  如何实现投票统计?
  投票统计是文件操作的又一个应用。一来,网站可以根据网民的投票结果,为自己的运营提供符合人们要求的决策信息;另外还可追踪人们对热点问题的看法,激发网民兴趣,提高网站的访问量。可谓一举两得。
  那么投票统计是如何实现的呢?他要用到何种技术呢?看了下面的例子,相信读者会找到答案。

 

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3