//从Servlet读取文件
package examples;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ReadingServlet extends HttpServlet{
private static final String CONTENT_TYPE="text/html";
private StringBuffer strBuf;
private String header;
public void init(ServletConfig config) throws ServletException{
super.init(config);
ServletContext context=config.getServletContext();
strBuf=new StringBuffer();
try{
BufferedReader bufRead=new BufferedReader(new InputStreamReader(
(context.getResourceAsStream("readme.txt"))));//这个readme.txt放入你的web应用的根目录
BufferedReader bufRead1=new BufferedReader(new InputStreamReader(
(getClass().getResourceAsStream("readme.txt"))));//这个readme.txt与类文件放在一起
while(bufRead.read()!=-1){
strBuf.append(bufRead.readLine());
}
while(bufRead1.read()!=-1){
strBuf.append(bufRead1.readLine());
}
bufRead.close();
bufRead1.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
header=strBuf.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<TITLE>Read File!</TITLE>");
out.println("<B>" +header+"</B>");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
doPost(request,response);
}
}