package com.mhb; import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class FileRead extends HttpServlet { public void init() throws ServletException {
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html"); //设置响应内容格式
response.setCharacterEncoding("gb2312"); //设置响应内容编码
PrintWriter out = response.getWriter(); //获得out对象
String fileName = "content.txt"; //指定文件名称
String realPath = request.getRealPath(fileName); File file = new File(realPath); if(file.exists()){
FileReader reader = new FileReader(file); //获得输入流
BufferedReader bufferReader = new BufferedReader(reader); //使用缓冲流
String line = null; //每行数据
while ((line = bufferReader.readLine()) != null){ //循环读取
out.print(line +"<br />"); //输出文件内容
}
}else{
out.print("文件不存在!");
} } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
} public void destroy() {
super.destroy();
}
}
文本文件:content.txt内容
Java编程
C++编程
C#编程
浏览器显示: