3 回答

TA贡献1946条经验 获得超3个赞
是的,您需要指定要读取的文件的编码。
是的,这意味着您必须知道要读取的文件的编码。
不,没有一般的方法可以猜测任何给定“纯文本”文件的编码。
的构造函数FileReader始终使用平台默认编码,这通常是一个坏主意。
您需要使用而不是FileReader 。new InputStreamReader(new FileInputStream(pathToFile), <encoding>)

TA贡献1851条经验 获得超4个赞
FileReader
使用Java的平台默认编码,该编码取决于运行它的计算机的系统设置,并且通常是该区域设置中用户中最受欢迎的编码。
如果此“最佳猜测”不正确,则必须显式指定编码。不幸的是,FileReader
不允许这样做(API中的主要监督)。相反,您必须使用文件new InputStreamReader(new FileInputStream(filePath), encoding)
,最好是从有关文件的元数据中获取编码。

TA贡献1876条经验 获得超6个赞
使用InputStreamReader的FileInputStream比直接使用FileReader更好,因为后者不允许您指定编码字符集。
这是一起使用BufferedReader,FileInputStream和InputStreamReader的示例,以便您可以从文件中读取行。
List<String> words = new ArrayList<>();
List<String> meanings = new ArrayList<>();
public void readAll( ) throws IOException{
String fileName = "College_Grade4.txt";
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileName), charset));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if( line.length() == 0 ) continue;
int idx = line.indexOf("\t");
words.add( line.substring(0, idx ));
meanings.add( line.substring(idx+1));
}
reader.close();
}
添加回答
举报