项目场景:
BufferWriter写入文件,中文乱码情况
问题描述:
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Student student = new Student();
String name = req.getParameter("username");
String age = req.getParameter("age");
String score = req.getParameter("score");
student.setName(name);
student.setAge(Integer.parseInt(age));
student.setScore(Integer.parseInt(score));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/Users/rong/IdeaProjects/itheima/javaweb/studentManager/stuInfo.txt",true),"UTF-8"));
bw.write(student.getName()+ "," + student.getAge() + "," + student.getScore());
bw.newLine();
bw.close();
//定时刷新给浏览器
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("success!2秒后将跳回添加页面!");
resp.setHeader("Refresh","2;url=/studentManager/index.jsp");
}
原因分析:
文件生成默认打开编码的设置不一样
解决方案:
我们只需在创建流时指定我们自己的编码即可。
将
BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/rong/IdeaProjects/itheima/javaweb/studentManager/stuInfo.txt",true));
换成
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/Users/rong/IdeaProjects/itheima/javaweb/studentManager/stuInfo.txt",true),"UTF-8"));
就可以了