Detailed description of the operation files and instances in Servlet, detailed description of servlet
Detailed description and examples of Operation files in Servlet
Because the Servlet is A. Java file, the Operation file in the servlet is the same as that in a common java file.
Main Code for reading files:
FileReader f=new FileReader("f:\\lissdy.txt");BufferedReader bw=new BufferedReader(f);
Read a row of data
String num=bw.readLine();
Be sure to close the file stream
bw.close();
The method for writing files is similar. The Code is as follows:
Read:
Package com. lissdy; import java. io. bufferedReader; import java. io. IOException; import java. io. printWriter; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import java. io. *; @ SuppressWarnings ("serial") public class ReadFile extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {try {res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); FileReader f = new FileReader ("d :\\ lissdy.txt"); BufferedReader bw = new BufferedReader (f); String num = bw. readLine (); bw. close (); pw. println ("the data read from the file is:" + num);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
Write:
Package com. lissdy; import java. io. IOException; import java. io. printWriter; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import java. io. *; @ SuppressWarnings ("serial") public class WriteFile extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {try {res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); // The flow from memory to disk is write (output stream) // The flow from disk file to memory is read (input stream) FileWriter f = new FileWriter ("d: \ lissdy.txt "); BufferedWriter bw = new BufferedWriter (f); bw. write ("How to write a try file"); pw. println ("writing data to a file"); bw. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!