java使用readUTF()读取中文抛出EOFException异常的处理方法

文本文件读取时,类DataInputStream是错误的正如文档所述,类DataInputStream用于从底层输入流中读取原始Java数据类型,而readUTF()使用某种修改的UTF-8格式(不是标准的UTF-8格式)。 
要从文本文件中读取,您应该使用Reader。java.io中存在的各种Reader类(例如BufferedReader,InputStreamReader,FileReader等)负责使用字符编码将数据从输入流转换为文本。 
解决方案一:

File file = new File("C:\MyFile.txt");
fis = new FileInputStream(file);
 
isr = new InputStreamReader(fis, "UTF-8");
br = new BufferedReader(isr);
 
String line;
while ((line = br.readLine()) != null) {
  System.out.println(line);
}

解决方案二:

使用:

new String(file.readLine().getBytes("ISO-8859-1"),"utf-8");

替代readUTF()来获取文本中的中文。

温润如玉,坚毅如铁。
原文地址:https://www.cnblogs.com/heisen/p/9960060.html