开发者

flushing input stream: java

Is there a way开发者_开发技巧 to flush the input stream in Java, perhaps prior to closing it? In relation to iteratively invoking the statements below, while reading several files on disk

InputStream fileStream = item.openStream();
fileStream.close;


InputStream cannot be flushed. Why do you want to do this? OutputStream can be flushed as it implements the interface Flushable. Flushing makes IMHO only sense in scenarios where data is written (to force a write of buffered data). Please see the documentation of Flushable for all implementing classes.


This is an old question but appears to be the only one of its kind, and I think there is a valid use case for "flushing" an input stream.

In Java, if you are using a BufferedReader or BufferedInputStream (which I believe is a common case), "flushing" the stream can be considered to be equivalent to discarding all data currently in the buffer -- i.e., flushing the buffer.

For an example of when this might be useful, consider implementing a REPL for a programming language such as Python or similar.

In this case you might use a BufferedReader on System.in. The user enters a (possibly large) expression and hits enter. At this point, the expression (or some part of it) is stored in the buffer of your Reader.

Now, if a syntax error occurs somewhere within the expression, it will be caught and displayed to the user. However, the remainder of the expression still resides in the input buffer.

When the REPL loop continues, it will begin reading just beyond the point where the syntax error occurred, in the middle of some erroneous expression. This is likely not desirable. Rather, it would be better to simply discard the remainder of the buffer and continue with a "fresh start."

In this sense, we can use the BufferedReader API method ready() to discard any remaining buffered characters. The documentation reads:

"Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready."

Then we can define a method to "flush" a BufferedReader as:

void flush(BufferedReader input) throws IOException
{
  while (input.ready())
    input.read();
}

which simply discards all remaining data until the buffer is empty. We then call flush() after handling a syntax error (by displaying to the user). When the REPL loop resumes you have an empty buffer and thus do not get a pile of meaningless errors caused by the "junk" left in the buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜