//Write.jsp
<%@ page contentType="text/html,charset=gb2312"%>
<html>
<head><title>写一个文件</title></head>
<body>
<%--创建javabean并设置属性--%>
<jsp:useBean id="writer" class="ch8.WriteFile" scope="request">
<jsp:setProperty name="writer" property="path" value="D:\\Tomcat 5.5\\webapps\\ROOT\\1\\write\\writefile.txt" />
<jsp:setProperty name="writer" property="something" value="初始化something属性" />
</jsp:useBean>
<h3>写一个文件</h3>
<p>
<%--设置要写入的字符串--%>
<% writer.setSomething("这是写到文件的内容");%>
<% out.println(writer.getSomething());%>
<%--调用writer的writeSomething方法写入文件并返回成功或者出错信息--%>
<% out.println(writer.writeSomething()); %>
</p>
</body>
</html>
//WriteFile.java
package ch8;
import java.io.*;
public class WriteFile
{
private String path; //文件路径
private String something; //写入的字符串
//初始化
public void WriteOver()
{
path=null;
something="缺省文字";
}
//设置文件路径
public void setPath(String apath)
{
path=apath;
}
//得到文件路径
public String getPath()
{
return path;
}
public void setSomething(String asomething)
{
something=asomething;
}
//设置字符串
public String getSomething()
{
return something;
}
//写入字符串到文件中,成功则返回success字符串
public String writeSomething()
{
try{
File f=new File(path);
PrintWriter out=new PrintWriter(new FileWriter(f));
out.print(this.getSomething()+"\n");
out.close();
return "success.";
}catch(IOException e)
{
return e.toString();
}
}
}
编译后,放到root目录打开后为文件保存的对话框,不是应该显示"
写一个文件
这是写到文件的内容.success.
"
哪位试一下,帮帮忙!