Serlvet学习笔记之四—对文件的操作
1.读文件
package com.demo; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import javax.servlet.http.*; public class ServletFileTest1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try { req.setCharacterEncoding("gb2312"); res.setContentType("text/html;charset=gb2312"); PrintWriter pw=res.getWriter(); //创建一个FileReader FileReader f=new FileReader("D:\\myCount.txt"); BufferedReader br=new BufferedReader(f); String numVal=br.readLine(); br.close(); //一定要关闭文件流 pw.println("从文件中读取的数据是: "+numVal); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req, res); } }
2.写文件
package com.demo; import java.io.*; import javax.servlet.http.*; public class ServletFileTest2 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res){ try { req.setCharacterEncoding("gb2312"); res.setContentType("text/html;charset=gb2312"); PrintWriter pw=res.getWriter(); //创建一个FileWriter FileWriter f=new FileWriter("D:\\myCount.txt"); BufferedWriter bw=new BufferedWriter(f); bw.write("hello"); //会把原来文件中的信息给删除掉,相当于> bw.close(); pw.println("向文件写入信息"); } catch (Exception e) { e.printStackTrace(); } } public void dopost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req, res); } }