从文本文件读取时,类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()来获取文本中的中文。