top
Loading...
jsp文件操作之寫入篇
p>文件操作是網站編程的重要內容之一,asp關于文件操作討論的已經很多了,讓我們來看看jsp中是如何實現的。
這里用到了兩個文件,一個jsp文件一個javabean文件,通過jsp中調用javabean可以輕松寫文本文件,注意請建立一個test目錄到web根目錄下,程序將會建立一個afile.txt文件,javabean文件編譯后將class文件放到對應的class目錄下(tomcat環境)。
有了在jsp下讀取和寫入文件的方法,要做出一個簡單的計數器來相信不是一件困難的事情了,大家可以嘗試一下:)

WriteOver.Jsp

$#@60;html$#@62;
$#@60;head$#@62;
$#@60;title$#@62;寫一個文件$#@60;/title$#@62;
$#@60;/head$#@62;
$#@60;body bgcolor="#000000"$#@62;
$#@60;%--創建javabean并設置屬性 --%$#@62;
$#@60;jsp:useBean id="writer" class="WriteOver" scope="request"$#@62;
$#@60;jsp:setProperty name="writer" property="path" value="/test/afile.txt" /$#@62;
$#@60;jsp:setProperty name="writer" property="something" value="初始化somthing屬性" /$#@62;
$#@60;/jsp:useBean$#@62;

$#@60;h3$#@62;寫一個文件$#@60;/h3$#@62;

$#@60;p$#@62;
$#@60;%--設置要寫入的字符串 --%$#@62;
$#@60;% writer.setSomething("寫點東西到文件"); %$#@62;
$#@60;%--讀取上面設置的字符串 --%$#@62;
$#@60;% out.print(writer.getSomething()); %$#@62;
$#@60;%--調用writer的writeSomething方法寫入文件并返回成功或者出錯信息 --%$#@62;
$#@60;% out.print(writer.writeSomething()); %$#@62;

$#@60;/p$#@62;
$#@60;/body$#@62;
$#@60;/html$#@62;

//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 Something() {
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();
}
}
}
為了對文件操作有全面了解,請看下一篇$#@60;$#@60;jsp文件操作之追加篇$#@62;$#@62;。

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗