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 used two files, a JSP file a JavaBean file, through the JSP call JavaBean can easily write text files, note Please create a test directory to the Web root directory, The program will create a afile.txt file, JavaBean the file after compiling the class file into the corresponding class directory (Tomcat Environment).
There is a way to read and write files under the JSP, to make a simple counter to believe that it is not a difficult thing, we can try:
writeover.jsp
<title> Write a file </title>
<body bgcolor= "#000000" >
<%--Create JavaBean and set properties--%>
<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= "Initialize somthing properties"/>
</jsp:useBean>
<p>
<%--sets the string to write--%>
<% writer.setsomething ("write something to a document"); %>
<%--reads the string set above--%>
<% Out.print (writer.getsomething ()); %>
<%--calls the writer Writesomething method to write to the file and returns a success or error message--%>
<% Out.print (writer.writesomething ()); %>
</p>
</body>
Writeover.java JavaBean File
Import java.io.*;
public class Writeover {
Private String path; File path
Strings written by private string something;//
Class
Public Writeover () {
Path = NULL;
something = "Default text";
}
Set file path
public void SetPath (String apath) {
Path = Apath;
}
Get file path
Public String GetPath () {
return path;
}
Get string
public void setsomething (String asomething) {
something = asomething;
}
Set string
Public String getsomething () {
return something;
}
Writes the string to the file, succeeds returns the success string
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 ();
}
}
}