SoFunction
Updated on 2025-03-10

Additional article of jsp file operation

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. By calling javabean in jsp, you can easily append data to text files. If you read the above and write it, you will find that this article has many similarities with the previous article, and it is easy to read.
Note: Please place a text file in the test directory of the web root directory so that the program can add data. After the javabean file is compiled, the class file is placed in the corresponding class directory (tomcat environment).



<html>
<head>
<title>Append data</title>
</head>
<body bgcolor="#000000">
<%--Create a javabean and set properties --%>
<jsp:useBean class="WriteAppend" scope="request">
<jsp:setProperty name="writer" property="path" value="/path/to/" />
<jsp:setProperty name="writer" property="something" value="initialize something property" />
</jsp:useBean>

<h3>Add data</h3>

<p>
<%--Set the string to be appended --%>
<% ("Append data"); %>
<%--Read the string set above --%>
<% (()); %>
<%--Application file by calling the writer's writeSomething method and returning successful or error message --%>
<% (()); %>

</p>
</body>
</html>

// javabean file
import .*;

public class WriteAppend {

private String path;//File path
private String something;//Add 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 be appended
public void setSomething(String asomething) {
something = asomething;
}
//Get the string to be appended
public String getSomething() {
return something;
}
//Append string
public String writeSomething() {
try {
//Create the file path and write something string, pay attention to the difference between writing and writing
FileWriter theFile = new FileWriter(path,true);
PrintWriter out = new PrintWriter(theFile);
(something + "
");
();
//Close the file and return the success string
();
return "success!!";
} catch (IOException e) {
return ();
}
}
}

OK, all the contents of this file operation have been completed. If you see this, I believe that your basic operation of the file is OK.