在Java中使用FileReader读取UTF-8编码文件
在Java中,FileReader类用于读取文件内容,但默认情况下,它使用系统默认的字符编码,这可能导致读取文件时出现乱码问题。为了确保正确读取UTF-8编码的文件,可以使用InputStreamReader类来指定字符编码。使用InputStreamReader读取UTF-8编码文件
InputStreamReader是一个桥接器,它将字节流转换为字符流。通过将FileInputStream与InputStreamReader结合使用,可以指定文件的字符编码为UTF-8,从而避免乱码问题。以下是一个示例代码:
import java.io.*;
public class FileReaderExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}




