我必须在读取文件之前检查文件的编码。为了检查编码,我使用了这个方法:
try {
CharsetDecoder decoder= Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
final InputStreamReader input = new InputStreamReader(is, decoder);
int data = input.read();
while(data != -1){
data = input.read();
}
input.close();
} catch (MalformedInputException e) {
LOGGER.error(The file encoding is wrong!");
throw new MalformedInputException(Math.toIntExact(file.length()));
}
}
下面是调用它的代码:
InputStream is = new FileInputStream(file);
checkFileEncoding(is);
List<MyObject> list = newArrayList();
try(CSVReader reader = new CSVReader(new InputStreamReader(is), ';')) {
list = reader.readAll().stream()
.skip(1) //
.map(myObjectMap)
.filter(o -> o != null)
.collect(toList());
}
问题是,当我之前调用 checkFileEncoding
时,我的列表是空的。我认为这是因为我读了我的文件两次。我应该怎么做?
最佳答案
final InputStreamReader input = new InputStreamReader(is, decoder);
您的 InputStreamReader 将从输入流中读取所有数据。这意味着不再有可用数据。此外,您已经将其关闭。
您需要创建一个 InputStream 两次。一次测试字符集,再一次实际读取数据。
所以改变
InputStream is = new FileInputStream(file);
checkFileEncoding(is);
到
InputStream is = new FileInputStream(file);
checkFileEncoding(is);
is = new FileInputStream(file);
也是在
之后try(CSVReader reader ..
..
}
添加
is.close();
关于java - 使用 InputStreamReader 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38079518/