Example of reading a file
*************************************************** *
<%@ page contentType="text/html;charset=gb2312"%>
<%
//Variable declaration
java.lang.String strFileName; //File name
java.io.File objFile; //File object
java.io.FileReader objFileReader; //Read file object
char[] chrBuffer = new char[10]; //buffer
int intLength; //The actual number of characters read (one Chinese character is one character)
//Set the file name to be read
strFileName = "d:\test.txt";
//Create file object
objFile = new java.io.File(strFileName);
//Determine whether the file exists
if(objFile.exists()){//File exists
//Create a read file object
objFileReader = new java.io.FileReader(objFile);
//Read file content
while((intLength=objFileReader.read(chrBuffer))!=-1){
//Output
out.write(chrBuffer,0,intLength);
}
//Close reading file object
objFileReader.close();
}
else{//The file does not exist
out.println("The following file does not exist:"+strFileName);
}
%>
***************************************************
Example of writing a file
***************************************************
Text files can be written using the PrintWriter object.
Please refer to the following example:
<%@ 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());
}
%>
Now, open imp.txt and view it. The string "print me" should have been written.
There is another method, using the file tag of the IN16 tag library, please refer to http://sourceforge.net/project/?group_id=1282.
The example syntax is:
<ext:file action="write|append|create|copy|move|delete|rename|read" from="<%= myfilename %>">
Redirect to: http://www.cnjsp.org