The class ReadFile needs to receive a PrintWriter parameter, resp.getWriter()
.
The character encoding was not handled both on reading the file, as on presenting it in the browser. Here I elected for both UTF-8.
For the file it might be Charset.forName("Windows-1252")
or such.
As the java Files class has everything that ReadFile could do, I used that.
@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));
}
Or using HTML formatting:
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("&", "&")
.replace("<", "<")
.replace(">", ">");
out.printl(line);
});
out.println("</pre></body></html>");
With using a ReadFile class:
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);
}