问题描述
我正在处理一些Java代码,其中读取了一个InputStream,然后需要使用相同的方法再次读取它.
I'm dealing with some Java code in which there's an InputStream that I read one time and then I need to read it once again in the same method.
问题是我需要将其位置重置为开始才能读取两次.
The problem is that I need to reset it's position to the start in order to read it twice.
我找到了解决该问题的方法:
I've found a hack-ish solution to the problem:
is.mark(Integer.MAX_VALUE);
//Read the InputStream is fully
// { ... }
try
{
is.reset();
}
catch (IOException e)
{
e.printStackTrace();
}
此解决方案是否会导致某些无法预期的行为?还是在愚蠢的情况下会起作用?
Does this solution lead to some unespected behaviours? Or it will work in it's dumbness?
推荐答案
按照书面说明,您不能保证,因为不需要 mark()
报告其是否成功.要获得保证,您必须先致电 markSupported(),它必须返回 true
.
As written, you have no guarantees, because mark()
is not required to report whether it was successful. To get a guarantee, you must first call markSupported(), and it must return true
.
如所写,指定的读取限制也是非常危险的.如果您碰巧使用的是在内存中缓冲的流,则它可能会分配2GB的缓冲区.另一方面,如果碰巧正在使用 FileInputStream
,就可以了.
Also as written, the specified read limit is very dangerous. If you happen to be using a stream that buffers in-memory, it will potentially allocate a 2GB buffer. On the other hand, if you happen to be using a FileInputStream
, you're fine.
更好的方法是将 BufferedInputStream
与显式缓冲区一起使用.
A better approach is to use a BufferedInputStream
with an explicit buffer.
这篇关于Java-重置InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!