jsp文件操作之追加篇
资源介绍
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();
}
}
}