如何在浏览器上打印文件的内容

时间:2018-04-05 11:47:30

标签: java servlets

ReadFile Class

public class  ReadFile {

    public void  readFile() throws IOException {

        BufferedReader is = new BufferedReader(new FileReader("D:\\text.txt"));

        if (is != null) {
            BufferedReader reader = new BufferedReader(is);
            String text;

            while ((text = reader.readLine()) != null) {

            }
            is.close();


        }
    }
    public static void  main(String[] args) throws IOException {

        ReadFile read=new ReadFile();
        read.readFile();
    }
}   

Servlet类

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
{
    resp.setContentType("text/html");

    ReadFile readfile = new ReadFile();
    readfile.readFile();
}

1 个答案:

答案 0 :(得分:0)

类ReadFile需要接收PrintWriter参数resp.getWriter()。 在读取文件时不会处理字符编码,就像在浏览器中显示它一样。在这里我选择了UTF-8。

对于文件,它可能是Charset.forName("Windows-1252")等。

由于java Files类具有ReadFile可以执行的所有操作,因此我使用了它。

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException 
{
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter out = resp.getWriter();
    Path path = Paths.get("D:\\text.txt");
    Files.lines(path, StandardCharsets.UTF_8)
        .forEach(out::println));
}

或使用HTML格式:

    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter out = resp.getWriter();
    out.println("<!DOCTYPE html>");
    out.println("<html><head>");
    out.println("<meta charset='UTF-8'>");
    out.println("<title>The text<title>");
    out.println("</head><body><pre>");
    Path path = Paths.get("D:\\text.txt");
    Files.lines(path, StandardCharsets.UTF_8)
        .forEach(line -> {
             line = line.replace("&", "&amp;")
                 .replace("<", "&lt;")
                 .replace(">", "&gt;");
             out.printl(line);
        });
    out.println("</pre></body></html>");

使用ReadFile类:

public class  ReadFile {

    public void  readFile(PrintWriter out) throws IOException {
        Path path = Paths.get("D:\\text.txt");
        Files.lines(path, StandardCharsets.UTF_8)
            .forEach(out::println));
    }

    public static void main(String[] args) throws IOException {   
        ReadFile read = new ReadFile();
        read.readFile(new PrintWriter(System.out));
    }
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException 
{
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter out = resp.getWriter();
    ReadFile read = new ReadFile();
    read.readFile(System.out);
}