Home  >  Article  >  Java  >  Introduction to solutions to garbled files when reading files in Java

Introduction to solutions to garbled files when reading files in Java

尚
Original
2019-12-05 10:07:413100browse

Introduction to solutions to garbled files when reading files in 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);

结果

Introduction to solutions to garbled files when reading files in Java

然而, 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);

结果

Introduction to solutions to garbled files when reading files in Java

使用InputStreamReader代替FileReader,并在构造函数中指定以GBK编码读取FileInputStream中的内容, 便能打印正确的结果。

更多java知识请关注java基础教程栏目。

The above is the detailed content of Introduction to solutions to garbled files when reading files in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn