Reputation: 14751
I wrote some binary data in a file using the FileOutputStream
class. Now I want to read it with the Scanner
class, but it can't. Is it possible to read a binary file with Scanner class? If yes, then how?
Edit:
I solve it by in.nextline();
Upvotes: 0
Views: 975
Reputation: 76709
Now I want to read it with the Scanner class, but it can't.
That is a correct observation. A Scanner will not read binary data, it is not designed for that purpose. Scanners expect to be provided with an object that implements the Readable interface, whose contract specifies that only characters may be returned. It can accept an InputStream, but as the API states: Bytes from the stream are converted into characters using the underlying platform's default charset.
Is it possible to read a binary file with Scanner class? If yes, then how?
Going by the previous explanation, it is not possible, not unless you've written them in a manner so that the above process of converting bytes returns characters. If you need access to binary data from a stream, you'll need to avoid using Readers and Readable objects. You'll need to work on raw InputStreams or FilterInputStreams, that will return byte arrays or suitable objects. In your specific case, you'll need a FileInputStream.
Tips:
Upvotes: 2
Reputation: 533442
To read a binary file you can use DataInputStream or ByteBuffer with NIO.
Upvotes: 2
Reputation: 24630
Did you read the API docs ?
A simple text scanner which can parse primitive types and strings using regular expressions.
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html
This may help you:
Best way to read structured binary files with Java
Upvotes: 1