获取字符集时流关闭错误

时间:2018-03-20 08:50:59

标签: java character-encoding inputstream bufferedreader

我遇到以下问题:

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项目并且它已被消费但我不确定。

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

提前多多感谢!

1 个答案:

答案 0 :(得分:1)

是的,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) {
    ...
}