Js
File operation is one of the important content of Web programming, ASP on file operation has been discussed a lot, let's see how JSP is implemented.
Here to use two files, a JSP file, a JavaBean file, through the JSP call JavaBean can easily append data to the text file, if you read on the written article, you will find this article with a lot of similarities, read it is also very easy.
Note Place a text file Afile.txt to the Web root test directory so that the program can append the data, and JavaBean the class file to the corresponding class directory (Tomcat Environment) after the file is compiled.
writeappend.jsp
<title> Append Data </title>
<body bgcolor= "#000000" >
<%--Create JavaBean and set properties--%>
<jsp:usebean id= "Writer" class= "writeappend" scope= "Request" >
<jsp:setproperty name= "Writer" property= "path" value= "/path/to/afile.txt"/>
<jsp:setproperty name= "Writer" property= "something" value= "Initialize something Properties"/>
</jsp:useBean>
<p>
<%--sets the string to append--%>
<% writer.setsomething ("additional data"); %>
<%--reads the string set above--%>
<% Out.print (writer.getsomething ()); %>
<%--calls the writer Writesomething method to append the file and returns a success or error message--%>
<% Out.print (writer.writesomething ()); %>
</p>
</body>
Writeappend.java JavaBean File
Import java.io.*;
public class Writeappend {
Private string path;//file path
private string something;//appended string variable
//initialization
Public writeappend () {
Path = Null
Something = "Default message";
}
//Set file path
public void SetPath (String apath) {
Path = Apath;
}
//Get file path
Public String GetPath () {
return path;
}
//Set the string to append
public void setsomething (string asomething) {
something = asomething;
}
//Get the string
public string getsomething () {
return something to append;
}
//Append string
public string writesomething () {
try {
///create file path and write something string, note the difference between and write articles
Fi Lewriter thefile = new FileWriter (path,true);
PrintWriter out = new PrintWriter (thefile);
Out.print (something + "
");
Out.close ();
//Close the file and return the success string
Thefile.close ();
return "success!!";
} catch (IOException e) {
return e.tostring ();
}
}
}
OK, all the contents of this file operation are complete, if you see here, I believe you are OK for the basic operation of the file.