简体   繁体   中英

Problem with Scanner class in java

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();

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM