Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I peek at the first two bytes in an InputStream?

Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?

Answer - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.

like image 814
Epaga Avatar asked Sep 29 '08 09:09

Epaga


People also ask

How do you read all bytes from InputStream?

Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.

Which stream reads 2 bytes at a time?

Java provides many character stream classes, but the most common ones are- FileReader- It is used to read two bytes at a time from the source. The following is the constructor to create an instance of the FileReader class. FileReader in = new FileReader("filename");


2 Answers

For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:

BufferedInputStream bis = new BufferedInputStream(inputStream); bis.mark(2); int byte1 = bis.read(); int byte2 = bis.read(); bis.reset(); // note: you must continue using the BufferedInputStream instead of the inputStream 
like image 91
Rasmus Faber Avatar answered Oct 14 '22 01:10

Rasmus Faber


You might find PushbackInputStream to be useful:

http://docs.oracle.com/javase/6/docs/api/java/io/PushbackInputStream.html

like image 31
Alex Miller Avatar answered Oct 13 '22 23:10

Alex Miller