欢迎来到陈宇翔的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

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()来获取文本中的中文。

posted on 2018-11-14 20:05  紫翼之狮  阅读(2945)  评论(0编辑  收藏  举报

导航