Servlet read/write operations on files, servlet read/write operations
(1) how to read the file content in serlvet
Package com. tsinghua; import java. io. *; import javax. servlet. http. *; public class ServletFileTest1 extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {try {// Chinese garbled res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); // create a FileReaderFileReader f = new FileReader ("f: \ myCounter.txt"); BufferedReader bw = new BufferedReader (f ); // read a row of data or use String numVal = bw for all content in the for loop. readLine (); // be sure to close the file stream bw. close (); pw. println ("the data read from the file is:" + numVal);} catch (Exception ex) {ex. printStackTrace () ;}} public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}
(2) how to write data to a file in serlvet
Package com. tsinghua; import java. io. *; import javax. servlet. http. *; public class ServletFileTest2 extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {try {// Chinese garbled res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); // create a FileWriter to view memory data-> Disk Files (write, output) // to view memory data <-disk files (read, input) fileWriter f = new FileWriter ("f: \ myCounter.txt"); BufferedWriter bw = new BufferedWriter (f); // write data bw to the file. write ("1"); // close the file stream bw. close (); pw. println ("data is written in the file");} catch (Exception ex) {ex. printStackTrace () ;}} public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}
How to define a Servlet, read the content of a text file, and print the content of the file on the page
The path in Serverlet is different from your project path.
The former is the path in the container, that is, the path your project publishes to Tomcat or other servers.
The latter is your local workspace path
You can use this method to obtain the absolute path.
File f = new File ("");
String absolutePath = f. getAbsolutePath ();
System. out. println (absolutePath );
// Read jms properties
File configFile = new File (absolutePath + "\ your_file_name.txt ");
If (configFile = null ){
Throw new Exception ("Configuration File Not Found: facs_fasg.properties ");
}
InputStream propertiesInStream = configFile. toURL (). openStream ();
How slow is File Reading Speed in java servlet!
The first access to the webpage you requested will be slow, because tomcat needs to compile jsp as a servlet, so try again if the second access is faster, you paste the logic code in jsp, to see if there is any loop and the like, garbled problem should be your jsp Encoding Problems, in general we recommend jsp encoding for UTF-8, for the setting method, see the following code:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %>