Nio 读取UTF-8文件出现中文乱码
错误代码
String filePath = "viewflow.html" ; StringBuilder sb = new StringBuilder(1024*10); try { BufferedReader reader = new BufferedReader(new FileReader(new File(filePath))); CharBuffer charBuff = CharBuffer.allocate(1024); int length = -1 ; while((length = reader.read(charBuff)) > 0 ){ charBuff.flip(); sb.append(charBuff,0,length); } System.out.println(sb.toString()); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
通过FileReader构造读取文本是,中文变为乱码。
解决办法:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
乱码问题可以解决。