servlet从服务器磁盘文件读出到浏览器显示,中文乱码问题,不要忘记在输入流和输出流都要设置编码格式,否则一个地方没设置不统一就会各种乱码
package com.swift; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/show") public class fromJsonFile extends HttpServlet { private static final long serialVersionUID = 1L; public fromJsonFile() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:/student.json"),"utf-8"));//这里不要忘记设置编码 String str; StringBuffer sb=new StringBuffer(); while((str=br.readLine())!=null) { sb.append(str); sb.append("\r\n"); } br.close(); response.getWriter().println(sb.toString()); System.out.println(sb.toString()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Never waste time any more, Never old man be a yong man