描述:将若干文本内容写入一个文件,然后读取这个文件,并将文件的内容显示给用户。
exampleWrite.jsp
<%@ page contentType="text/html; charset=GB2312" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="file" %>
<HTML><BODY bgcolor="green">
<FORM action="" method="post">
请输入文件的内容:<BR />
<TEXTAREA name="write" rows="6" cols="20"></TEXTAREA>
<INPUT type="submit" value="提交" />
</FORM>
<%
String str = request.getParameter("write");
if (str == null) {
str = "";
}
str = new String(str.getBytes("ISO-8859-1"));
%>
<file:WriteTag dir="E:/JSP/" fileName="file02.txt" content="<%=str%>" />
<A href="exampleRead.jsp">查看写入的内容</A>
</BODY></HTML>
exampleRead.jsp
<%@ page contentType="text/html; charset=GB2312" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="file" %>
<HTML><BODY bgcolor="green">
<file:ReadTag dir="E:/JSP/" fileName="file02.txt" />
从文件中读取的内容:<BR />
<TEXTAREA name="read" rows="6" cols="20"><%=result%></TEXTAREA>
</BODY></HTML>
Write.tag
<%@ tag pageEncoding="GB2312" %>
<%@ tag import="java.io.*" %>
<%@ attribute name="dir" required="true" %>
<%@ attribute name="fileName" required="true" %>
<%@ attribute name="content" type="java.lang.String" required="true" %>
<%!
public void writeContent(String str, File f) {
try {
BufferedWriter bufout = new BufferedWriter(new FileWriter(f));
bufout.write(str);
bufout.close();
} catch (IOException ex) {
//out.print(ex);
}
}
%>
<%
File mulu = new File(dir);
mulu.mkdir();
File f = new File(mulu, fileName);
if (content.length() > 0) {
writeContent(content, f);
out.println("成功写入");
}
%>
Read.tag
<%@ tag import="java.io.*" %>
<%@ attribute name="dir" required="true" %>
<%@ attribute name="fileName" required="true" %>
<%@ variable name-given="result" scope="AT_END" %>
<%!
public String readContent(File f) {
StringBuffer str = new StringBuffer();
try {
BufferedReader bufin = new BufferedReader(new FileReader(f));
String temp;
while ((temp=bufin.readLine()) != null) {
str.append(temp);
}
bufin.close();
} catch (IOException ex) {
//out.print(ex);
}
return new String(str);
}
%>
<%
File f = new File(dir, fileName);
String fileContent = readContent(f);
jspContext.setAttribute("result", fileContent);
%>
容易出现的编译错误:
1、str = new String(str.getBytes("ISO-8859-1"));写成str = new String(new byte[](str.getBytes("ISO-8859-1")));。
2、函数没有写返回值。
3、读写文件的路径不一致。