获取字符集时流关闭错误

Stream closed error when getting charset

我在使用以下代码时遇到问题:

try (
      InputStream is = new FileInputStream(file);
      BufferedReader br = new BufferedReader(
                   new InputStreamReader(is,
                     Charset.forName(SidFileUtils.charsetDetection(is))
                   )
                 );
    ) {

        br.readLine();
        br.readLine();

        for (String line = br.readLine() ; line != null ; line = br.readLine()) {
            lines.add(line);
        }
    } catch (ExceptionTechnique | IOException e) {
        LOG.error("Erreur lors de la lecture du fichier " + file.getName(), e);
    }

这部分代码:Chasrset.forName(...) 给我一个 Stream Closed error。我认为这是因为我使用了两次 InputStream 项目并且它已经被消耗但我不确定。

你能帮我理解这段代码有什么问题吗?

提前致谢!

是的,charsetDetection 没有其他选项可以进一步读取流。某些流可以标记和重置读取位置特定的 InputStream 支持它时。

if (in.markSupported()) {
    final int maxBytesNeededForDetection = 8192;
    in.mark(maxBytesNeededForDetection);
    ... do the detection
    in.reset();
} else {
    throw IllegalState();
}

BufferedInputStream 确实支持它,但仅限于缓冲区大小;否则会引发 IOException("Resetting to invalid mark");

然后应该在构造函数中指定缓冲区大小。

在这种情况下似乎没有mark/reset被检测使用。非常合乎逻辑,因为这种技术的部分覆盖。

Charset charset = null;
try (InputStream is = new FileInputStream(file)) {
    Charset charset = Charset.forName(SidFileUtils.charsetDetection(is));
}
if (charset != null) {
    ...
}