1 package com.mhb; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.io.PrintWriter; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 public class FileRead extends HttpServlet { 15 16 public void init() throws ServletException { 17 } 18 19 public void doGet(HttpServletRequest request, HttpServletResponse response) 20 throws ServletException, IOException { 21 response.setContentType("text/html"); //设置响应内容格式 22 response.setCharacterEncoding("gb2312"); //设置响应内容编码 23 PrintWriter out = response.getWriter(); //获得out对象 24 String fileName = "content.txt"; //指定文件名称 25 String realPath = request.getRealPath(fileName); 26 27 File file = new File(realPath); 28 29 if(file.exists()){ 30 FileReader reader = new FileReader(file); //获得输入流 31 BufferedReader bufferReader = new BufferedReader(reader); //使用缓冲流 32 String line = null; //每行数据 33 while ((line = bufferReader.readLine()) != null){ //循环读取 34 out.print(line +"<br />"); //输出文件内容 35 } 36 }else{ 37 out.print("文件不存在!"); 38 } 39 40 } 41 42 public void doPost(HttpServletRequest request, HttpServletResponse response) 43 throws ServletException, IOException { 44 } 45 46 public void destroy() { 47 super.destroy(); 48 } 49 }
文本文件:content.txt内容
Java编程 C++编程 C#编程
浏览器显示: