jsp文件操作之追加篇

  文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看jsp中是如何实现的。

  这里用到了两个文件,一个jsp文件一个javabean文件,通过jsp中调用javabean可以轻松追加数据到文本文件,如果大家读了上写入篇的话,会发现这篇文章同上一篇有很多相似之处,读起来也很容易了。

  注意请放置一个文本文件afile.txt到web根目录的test目录下,以便程序追加数据,javabean文件编译后将class文件放到对应的class目录下(tomcat环境)。

  writeAppend.jsp

  <html>

  <head>

  <title>追加数据</title>

  </head>

  <body bgcolor="#000000">

  <%--创建javabean并设置属性 --%>

  <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属性" />

  </jsp:useBean>

  <h3>追加数据</h3>

  <p>

  <%--设置要追加的字符串 --%>

  <% writer.setSomething("追加数据"); %>

  <%--读取上面设置的字符串 --%>

  <% out.print(writer.getSomething()); %>

  <%--调用writer的writeSomething方法追加文件并返回成功或者出错信息 --%>

  <% out.print(writer.writeSomething()); %>

  </p>

  </body>

  </html>

  //WriteAppend.java javabean文件

  import java.io.*;

  public class WriteAppend {

  private String path;//文件路径

  private String something;//追加的字符串变量

  //初始化

  public WriteAppend() {

  path = null;

  something = "Default message";

  }

  //设置文件路径

  public void setPath(String apath) {

  path = apath;

  }

  //得到文件路径

  public String getPath() {

  return path;

  }

  //设置要追加的字符串

  public void setSomething(String asomething) {

  something = asomething;

  }

  //得到要追加的字符串

  public String getSomething() {

  return something;

  }

  //追加字符串

  public String writeSomething() {

  try {

     //创建文件path并写入something字符串,注意和写入篇的区别

  FileWriter theFile = new FileWriter(path,true);

  PrintWriter out = new PrintWriter(theFile);

    out.print(something + "

  ");

    out.close();

  //关闭文件并返回success字符串

    theFile.close();

    return "success!!";

  } catch (IOException e) {

     return e.toString();

  }    

  }

  }

  好了,到此文件操作的全部内容都完成了,如果您看到这里,相信您对文件基本操作已经OK了。