当使用文件流读取文本文件时,如果遇到中文字符,将会读到乱码.
用byte数组存储读取结果,再用byte数组构建字符串,可解决乱码问题
import java.io.File;
import java.io.FileInputStream;
public class ReadText {
public static String getText(String path) throws Exception {
FileInputStream in = new FileInputStream(path);
byte[] bit = new byte[in.available()];
in.read(bit);
in.close();
return (new String(bit));
}
//测试函数
public static void main(String[] a) throws Exception{
//从磁盘读取文本文件并打印
String str = ReadText.getText("c:/hello.txt");
System.out.println(str);
}
}