java读文件乱码解决方法引见【JAVA教程】,java,乱码

运用java读取磁盘文件内容轻易涌现乱码, 问题是因为java运用的编码和被读取文件的编码不一致致使的。(引荐:java视频教程)
假设有一个test.txt的文本文件,文件内容为:“测试java读取中文字符串乱码问题”, 个中包括中文,文件的编码花样为GBK。 如果我们运用的java平台默许编码为UTF-8
可运用
System.out.println(Charset.defaultCharset());
打印检察
那末当我们运用不指定编码的体式格局读取文件内容时,获得的效果将会是乱码
String path = "C:\\Users\\宏鸿\\Desktop\\test.txt"; FileReader fileReader = new FileReader(path); char[] chars = new char[1024]; String content = ""; while (fileReader.read(chars) > 0 ) { content += new String( chars ); } System.out.println(content);
效果
但是, Java IO 体系Reader系列中的FileReader是没有办法指定编码的,而FileReader的父类InputStreamReader能够指定编码,所以我们能够运用它来处理乱码问题
String path = "C:\\Users\\宏鸿\\Desktop\\test.txt"; FileInputStream fis = new FileInputStream(path); InputStreamReader inputStreamReader = new InputStreamReader(fis, "GBK"); char[] chars = new char[1024]; String content = ""; while (inputStreamReader.read(chars) > 0 ) { content += new String( chars ); } System.out.println(content);
效果
运用InputStreamReader替代FileReader,并在组织函数中指定以GBK编码读取FileInputStream中的内容, 便能打印准确的效果。
更多java学问请关注java基础教程栏目。
以上就是java读文件乱码处理方法引见的细致内容,更多请关注ki4网别的相干文章!