我在使用以下代码时遇到问题:
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 错误
。我认为这是因为我使用了 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");
。
然后应该在构造函数中指定缓冲区大小。
在这种情况下,检测似乎没有使用标记/重置
。这是非常合乎逻辑的,因为这种技术的部分覆盖。
Charset charset = null;
try (InputStream is = new FileInputStream(file)) {
Charset charset = Charset.forName(SidFileUtils.charsetDetection(is));
}
if (charset != null) {
...
}
关于java - 获取字符集时流关闭错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379770/