简体   繁体   English

java 中的扫描仪 class 出现问题

[英]Problem with Scanner class in java

I wrote some binary data in a file using the FileOutputStream class.我使用FileOutputStream class 在文件中写入了一些二进制数据。 Now I want to read it with the Scanner class, but it can't.现在我想用Scanner class 阅读它,但它不能。 Is it possible to read a binary file with Scanner class?是否可以使用扫描仪 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.要读取二进制文件,您可以将 DataInputStream 或 ByteBuffer 与 NIO 一起使用。

Now I want to read it with the Scanner class, but it can't.现在我想用扫描仪 class 阅读它,但它不能。

That is a correct observation.这是一个正确的观察。 A Scanner will not read binary data, it is not designed for that purpose. Scanner 不会读取二进制数据,它不是为此目的而设计的。 Scanners expect to be provided with an object that implements the Readable interface, whose contract specifies that only characters may be returned.扫描仪希望获得一个实现Readable接口的 object,其合同规定只能返回字符。 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.它可以接受 InputStream, 但正如 API 所述来自 stream 的字节使用底层平台的默认字符集转换为字符。

Is it possible to read a binary file with Scanner class?是否可以使用扫描仪 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.如果您需要从 stream 访问二进制数据,则需要避免使用Readers和 Readable 对象。 You'll need to work on raw InputStreams or FilterInputStreams , that will return byte arrays or suitable objects.您需要处理原始InputStreamsFilterInputStreams ,这将返回字节 arrays 或合适的对象。 In your specific case, you'll need a FileInputStream .在您的特定情况下,您将需要一个FileInputStream

Tips:提示:

  1. Use Reader and Writer objects when working with characters in Java.使用 Java 中的字符时使用 Reader 和Writer对象。
  2. Avoid using the above for binary data.避免将上述内容用于二进制数据。 Use InputStreams and OutputStreams instead.请改用 InputStreams 和 OutputStreams。
  3. Understand how the decorator pattern is implemented in java.io .了解如何在 java.io 中实现装饰器模式

Did you read the API docs?您是否阅读过 API 文档?

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.htmlhttp://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 使用 Java 读取结构化二进制文件的最佳方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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