读文件异常:java.nio.charset.MalformedInputException

匿名 (未验证) 提交于 2019-12-02 21:53:52
 public static void main(String[] args) throws IOException {         String content = Files.readAllLines(Paths.get("C:/Users/DELL/Desktop/1.txt")).stream()                 .collect(Collectors.joining("\n"));          System.out.println(content);     }

读取文件内容,但是在执行‘Files.readAllLines(path);’时,出现异常:java.nio.charset.MalformedInputException: Input length = 1。

查看源码发现:

public static BufferedReader newBufferedReader(Path path) throws IOException {           return newBufferedReader(path, StandardCharsets.UTF_8);       }  
而我要读的文件呢,是GBK!

也就是说,只要用GBK格式来读就可以了。修改如下:

 public static void main(String[] args) throws IOException {         String content = Files.readAllLines(Paths.get("C:/Users/DELL/Desktop/1.txt"), Charset.forName("GBK")).stream()                 .collect(Collectors.joining("\n"));          System.out.println(content);     }


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!