【问题标题】:Can't read same InputStream twice [duplicate]无法两次读取相同的 InputStream [重复]
【发布时间】:2018-10-24 04:30:40
【问题描述】:

我有一个 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());

【问题讨论】:

  • 为什么不存储第一次读取的值?解释更多,存储 nameFile 和流两次是不可能的?

标签: java inputstream


【解决方案1】:

由于 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();

【讨论】:

  • 如果内部读取流,您是否知道读取流的方法。直到 Spring 已经调用了 read 函数之后,我才在我的代码中收到它。有可能吗?
【解决方案2】:

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); 

【讨论】:

  • 经过测试,是否支持。将尝试通过复制到数组来重新读取。
  • 如果您的输入流支持它,您应该调用mark(int byteCountAbleToReset)。然后调用reset() 以返回流中的byteCountAbleToReset 字节。
  • 是的,我尝试了fileStream.mark(arrayList.size());然后fileStream.reset();,但没有成功
  • 您必须在从输入流中读取之前调用mark()。而传递的数字就是你要返回的字节数,肯定大于list.size()
  • 是的,在工作之前调用mark(),我在阅读部分之后得到它
猜你喜欢
  • 1970-01-01
  • 2012-09-10
  • 2011-08-10
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多