讀文件的例子
***************************************************
<%@ page contentType="text/html;charset=gb2312"%>
<%
//變量聲明/
java.lang.String strFileName; //文件名
java.io.File objFile; //文件對象
java.io.FileReader objFileReader; //讀文件對象
char[] chrBuffer = new char[10]; //緩沖
int intLength; //實際讀出的字符數(一個中文為一個字符)
//設置待讀文件名
strFileName = "d://test.txt";
//創建文件對象
objFile = new java.io.File(strFileName);
//判斷文件是否存在
if(objFile.exists()){//文件存在
//創建讀文件對象
objFileReader = new java.io.FileReader(objFile);
//讀文件內容
while((intLength=objFileReader.read(chrBuffer))!=-1){
//輸出
out.write(chrBuffer,0,intLength);
}
//關閉讀文件對象
objFileReader.close();
}
else{//文件不存在
out.}
%>
**************************************************
寫文件的例子
**************************************************
使用PrintWriter對象即可寫Text文件。
請參考以下示例:
<%@ page import="java.io.*" %>
<%
String str = "print me";
//always give the path from root. This way it almost always works.
String nameOfTextFile = "/usr/anil/imp.txt";
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(str);
//clean up
pw.close();
} catch(IOException e) {
out.println(e.getMessage());
}
%>
現在,打開imp.txt加以查看,字符串"print me"應該已經寫入。
還有另一種方法,使用IN16標記庫的file tag,可參考http://sourceforge.net/project/?group_id=1282.
其示例的語法為:
<ext:file action="write|append|create|copy|move|delete|rename|read" from="<%= myfilename %>">
轉:http://www.cnjsp.org
新聞熱點
疑難解答