0

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();
Mahdi_Nine
  • 14,205
  • 26
  • 82
  • 117

3 Answers3

2

To read a binary file you can use DataInputStream or ByteBuffer with NIO.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • i want to use from scanner class – Mahdi_Nine Jun 12 '11 at 09:16
  • @mehdi, Can you explain why using a Scanner is a requirement? You could use Scanner with a lot of work. You would still need to use DataInputStream to convert the data to text for the Scanner to consume. This would be pointless unless you have an existing library which only accepts a Scanner. – Peter Lawrey Jun 12 '11 at 09:30
2

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:

  1. Use Reader and Writer objects when working with characters in Java.
  2. Avoid using the above for binary data. Use InputStreams and OutputStreams instead.
  3. Understand how the decorator pattern is implemented in java.io.
Community
  • 1
  • 1
Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
1

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

Community
  • 1
  • 1
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
  • i saw it but didn't see any thing that could help me! – Mahdi_Nine Jun 12 '11 at 09:12
  • @mehdi, did it not occur to you that binary data is not exactly the same as primitive types and strings? To emphasize the portion of the extract posted by Peter: A simple **text** scanner which can parse primitive types and strings using regular expressions. – Vineet Reynolds Jun 12 '11 at 09:15
  • @mehdi, Then why are you insisting on using a Scanner? – Vineet Reynolds Jun 12 '11 at 09:18