示例:Servlet读取文件内容并在页面打印输出

 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#编程

浏览器显示:

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值