This article is based on the implementation of the tomcat platform. The file directory is:
Under tom_homewebappsews:
└ Html
✓ WEB-INF
Classes
└ Com
Using FileMan. class
└ FileServlet. class
Web. xml
On the homepage, we first implement the File Reading Class: FileMan. java
// A class for FileMan. java to read and write files
Package com;
Import java. io .*;
Public class FileMan {
Private String currentRecord = null; // variable for saving text
Private BufferedReader file; // BufferedReader object, used to read file data
Private String path; // complete file path name
Public FileMan (){
}
// The ReadFile method is used to read the data in the file filePath and return the data.
Public String ReadFile (String filePath) throws FileNotFoundException
{
Path = filePath;
// Create a new BufferedReader object
File = new BufferedReader (new FileReader (path ));
String returnStr = null;
Try
{
// Read a row of data and save it to the currentRecord variable
CurrentRecord = file. readLine ();
}
Catch (IOException e)
{// Handle errors
System. out. println ("Data reading error .");
}
If (currentRecord = null)
// If the file is empty
ReturnStr = "no record ";
Else
{// The file is not empty.
ReturnStr = currentRecord;
}
// Return the data to read the file
Return returnStr;
}
// Write a file
Public void WriteFile (String filePath, String tempcon) throws FileNotFoundException
{
Path = filePath;
Try {
// Create a PrintWriter object for writing data to a file
PrintWriter pw = new PrintWriter (new FileOutputStream (filePath ));
// Print the integer Writestr in text format
Pw. println (tempcon );
// Clear the PrintWriter object
Pw. close ();
} Catch (IOException e ){
// Handle errors
System. out. println ("file writing error" + e. getMessage ());
}
}
/* Below, you can test the java application to read files. After removing the preceding "//", you can run java FileMan to test the file. */
// Public static void main (String args [])
//{
// FileMan fm = new FileMan ();
// Try
//{
// Fm. WriteFile ("test.txt", "asf ");
//}
// Catch (FileNotFoundException e ){}
//}
}