标签:httpservlet servlet javaee 读取文件 io
(1)如何在serlvet中读取文件的内容
package com.tsinghua; import java.io.*; import javax.servlet.http.*; public class ServletFileTest1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try { //中文乱码 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //创建一个FileReader FileReader f=new FileReader("f:\\myCounter.txt"); BufferedReader bw=new BufferedReader(f); //读出一行数据 或者使用for循环都区全部内容 String numVal=bw.readLine(); //一定要关闭文件流 bw.close(); pw.println("从文件中读取的数据是:"+numVal); } catch (Exception ex) { ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
package com.tsinghua; import java.io.*; import javax.servlet.http.*; public class ServletFileTest2 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res){ try { //中文乱码 res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //创建一个FileWriter 看内存数据 -> 磁盘文件(写入,输出) //看内存数据 <- 磁盘文件(读入,输入) FileWriter f=new FileWriter("f:\\myCounter.txt"); BufferedWriter bw=new BufferedWriter(f); //在文件中写入数据 bw.write("1"); //关闭文件流 bw.close(); pw.println("在文件中写入了数据"); } catch (Exception ex) { ex.printStackTrace(); } } public void doPost(HttpServletRequest req,HttpServletResponse res){ this.doGet(req,res); } }
标签:httpservlet servlet javaee 读取文件 io
原文地址:http://blog.csdn.net/xlgen157387/article/details/38975683