File operations are an important part of website programming. asp has discussed a lot about file operations. Let's take a look at how jsp is implemented.
Compile file. After compiling the javabean file, place the class file in the corresponding class directory (tomcat environment ).
With the method of reading and writing files in jsp, it is not difficult to make a simple counter. You can try it :)
WriteOver. Jsp
<Html>
<Head>
<Title> write a file </title>
</Head>
<Body bgcolor = "#000000" type = "codeph" text = "/codeph">
<% -- Create a 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 = "Initializing somthing attributes"/>
</Jsp: useBean>
<H3> write a file
<P>
<% -- Set the string to be written -- %>
<% Writer. setSomething ("writing something to a file"); %>
<% -- Read the string set above -- %>
<% Out. print (writer. getSomething (); %>
<% -- Call writer's writeSomething method to write data to the file and return the success or error message -- %>
<% Out. print (writer. writeSomething (); %>
</P>
</Body>
</Html>
// WriteOver. java javabean file
Import java. io .*;
Public class WriteOver {
Private String path; // file path
Private String something; // The Written String
// Initialization
Public WriteOver (){
Path = null;
Something = "default text ";
}
// Set the file path
Public void setPath (String apath ){
Path = apath;
}
// Obtain the file path
Public String getPath (){
Return path;
}
// Obtain the string
Public void setSomething (String asomething ){
Something = asomething;
}
// Set the string
Public String getSomething (){
Return something;
}
// Write the string to the file. If the string is successfully written, the success string is returned.
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 ();
}
}
}