jsp文件操作之写入篇

文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看jsp中是如何实现的。
这里用到了两个文件,一个jsp文件一个javabean文件,通过jsp中调用javabean可以轻松写文本文件,注意请建立一个test目录到web根目录下,程序将会建立一个afile.txt文件,javabean文件编译后将class文件放到对应的class目录下(tomcat环境)。
有了在jsp下读取和写入文件的方法,要做出一个简单的计数器来相信不是一件困难的事情了,大家可以尝试一下:)

WriteOver.Jsp

1<html>
2<head>
3<title>写一个文件</title>
4</head>
5<body bgcolor="#000000">   

--创建javabean并设置属性 --

1<jsp:usebean class="WriteOver" id="writer" scope="request">
2<jsp:setproperty name="writer" property="path" value="/test/afile.txt"></jsp:setproperty>
3<jsp:setproperty name="writer" property="something" value="初始化somthing属性"></jsp:setproperty>
4</jsp:usebean>
5<h3>写一个文件</h3>
6<p>   

--设置要写入的字符串 --

writer.setSomething("写点东西到文件");

--读取上面设置的字符串 --

out.print(writer.getSomething());

--调用writer的writeSomething方法写入文件并返回成功或者出错信息 --

out.print(writer.writeSomething());

1  
2</p>
3</body>
4</html>

//WriteOver.java javabean文件
import java.io.*;

public class WriteOver {

private String path; //文件路径
private String something;//写入的字符串
//初始化
public 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() + "
");
out.close();
return "Success.";
} catch (IOException e) {
return e.toString();
}
}
}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus