File operation is one of the important contents of website programming. Asp has discussed a lot about file operation. Let’s take a look at how it is implemented in JSP.
Two files are used here, one jsp file and one javabean file. You can easily write text files by calling javabean in jsp. Please note that you need to create a test directory to the web root directory. The program will create a file. After the javabean file is compiled, the class file is placed in the corresponding class directory (tomcat environment).
With the method of reading and writing files under jsp, it is not difficult to make a simple counter. You can try it:)
<html>
<head>
<title>Write a file</title>
</head>
<body bgcolor="#000000">
<%--Create a javabean and set properties --%>
<jsp:useBean class="WriteOver" scope="request">
<jsp:setProperty name="writer" property="path" value="/test/" />
<jsp:setProperty name="writer" property="something" value="initialize the somthing property" />
</jsp:useBean>
<h3>Write a file</h3>
<p>
<%--Set the string to be written --%>
<% ("Write something to file"); %>
<%--Read the string set above --%>
<% (()); %>
<%--Call the writeSomething method of the writer to write to the file and return the successful or error message --%>
<% (()); %>
</p>
</body>
</html>
// javabean file
import .*;
public class WriteOver {
private String path; //File path
private String something;//Written string
//initialization
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 the string
public void setSomething(String asomething) {
something = asomething;
}
//Set string
public String getSomething() {
return something;
}
//Write the string into the file, and if it succeeds, it returns the success string.
public String writeSomething() {
try {
File f = new File(path);
PrintWriter out = new PrintWriter(new FileWriter(f));
(() + "
");
();
return "Success.";
} catch (IOException e) {
return ();
}
}
}