gpt4 book ai didi

java - MalformedInputException 与 Files.readAllLines()

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:32 25 4
gpt4 key购买 nike

我正在遍历一些文件,准确地说是 5328。这些文件是最多 60-200 行的普通 XML 文件。它们首先通过解析路径的简单方法 isXmlSourceFile 进行过滤。

    Files.walk(Paths.get("/home/me/development/projects/myproject"), FileVisitOption.FOLLOW_LINKS)
.filter(V3TestsGenerator::isXmlTestSourceFile)
.filter(V3TestsGenerator::fileContainsXmlTag)

最大的问题是第二个过滤器,尤其是方法 fileContainsXmlTag。对于每个文件,我想检测它的行中是否至少包含一次模式:

private static boolean fileContainsXmlTag(Path path) {
try {
return Files.readAllLines(path).stream().anyMatch(line -> PATTERN.matcher(line).find());
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

对于某些文件我得到了这个异常

java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at java.nio.file.Files.readAllLines(Files.java:3205)
at java.nio.file.Files.readAllLines(Files.java:3242)

但是当我使用 FileUtiles.readLines() 而不是 Files.readAllLines 时,一切都变得很好。

这是一个好奇心问题,所以如果有人知道发生了什么事,我们会很高兴。

谢谢

最佳答案

方法Files.readAllLines()假设您正在阅读的文件是用 UTF-8 编码的。

如果您收到此异常,那么您正在读取的文件很可能使用与 UTF-8 不同的字符编码进行编码。

找出使用的是什么字符编码,使用其他readAllLines方法,允许您指定字符编码。

例如,如果文件以 ISO-8859-1 编码:

return Files.readAllLines(path, StandardCharsets.ISO_8859_1).stream()... // etc.

FileUtiles.readLines() 方法(从哪里来的?)可能假设了其他东西(它可能假设文件是​​你系统的默认字符编码,这不是UTF-8)。

关于java - MalformedInputException 与 Files.readAllLines(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38828830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com