文件操作是網站編程的重要內容之一,asp關于文件操作討論的已經很多了,讓我們來看看jsp中是如何實現的。 這里用到了兩個文件,一個jsp文件一個javabean文件,通過jsp中調用javabean可以輕松寫文本文件,注意請建立一個test目錄到web根目錄下,程序將會建立一個afile.txt文件,javabean文件編譯后將class文件放到對應的class目錄下(tomcat環境)。 有了在jsp下讀取和寫入文件的方法,要做出一個簡單的計數器來相信不是一件困難的事情了,大家可以嘗試一下:)
WriteOver.Jsp
<html> <head> <title>寫一個文件</title> </head> <body bgcolor="#000000"> <%--創建javabean并設置屬性 --%> <jsp:useBean id="writer" class="WriteOver" scope="request"> <jsp:setProperty name="writer" property="path" value="/test/afile.txt" /> <jsp:setProperty name="writer" property="something" value="初始化somthing屬性" /> </jsp:useBean>
<h3>寫一個文件</h3>
<p> <%--設置要寫入的字符串 --%> <% writer.setSomething("寫點東西到文件"); %> <%--讀取上面設置的字符串 --%> <% out.print(writer.getSomething()); %> <%--調用writer的writeSomething方法寫入文件并返回成功或者出錯信息 --%> <% out.print(writer.writeSomething()); %>
</p> </body> </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(); } } }
|