• 示例: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#编程

    浏览器显示:

  • 相关阅读:
    Lombok Pojo默认初始值问题
    spring boot打包以及centos下部署
    Spring事件监听ApplicationListener源码流程分析
    synchronized是什么,用法及原理
    Spring动态切换数据源及事务
    linux环境中关闭tomcat,通过shutdown.sh无法彻底关闭--线程池
    LVS之DR模式
    LVS之ipvsadm命令
    LVS之NAT模式
    tcpdump抓包命令
  • 原文地址:https://www.cnblogs.com/tdcqma/p/4757564.html
Copyright © 2020-2023  润新知