我有一个InputStream作为参数,当我第一次读取它时工作正常,但是,读取相同的InputStream不起作用。我无法让mark()
和reset()
工作。有谁知道如何重置这个?我正在读一个.txt文件。该文件包含不再出现的敌人对象的生成值,因为输入流标记(?)在最后,我猜?
readTxt(InputStream resource){
//resource is a .txt as ResourceStream
arrayList = new BufferedReader(new InputStreamReader(resource,
StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
答案 0 :(得分:4)
mark()
仅在输入流支持时才有效(您可以markSupported()
查看。
它不适用于每个流。
读取输入流的一种方法是将输入流的内容复制到数组并重新读取数组:
byte[] buffer = new byte[2048];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int byteCount;
while ((byteCount = inputStream.read(buffer)) != -1)
{
output.write(buffer, 0, byteCount);
}
byte[] source = output.toByteArray();
// Now you have ability to reread the "secondary" input stream:
InputStream is = new ByteArrayInputStream(source);
答案 1 :(得分:0)
由于InputStream为markSupported()
,我可以使用mark()
和reset()
。
//mark 0, before you start reading your file
inputStream.mark(0);
//read your InputStream here
read(inputStream)...
//reset the stream, so it's ready to be read from the start again.
inputStream.reset();