java中Scanner类的问题

发布于 2024-11-14 23:04:08 字数 181 浏览 3 评论 0原文

我使用 FileOutputStream 类在文件中写入了一些二进制数据。现在我想用 Scanner 类读取它,但它不能。是否可以使用 Scanner 类读取二进制文件?如果是,那么如何?

编辑:

I solve it by in.nextline();

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情栀口红 2024-11-21 23:04:08

要读取二进制文件,您可以将 DataInputStream 或 ByteBuffer 与 NIO 结合使用。

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

Bonjour°[大白 2024-11-21 23:04:08

现在我想用 Scanner 类读取它,但它不能。

这是一个正确的观察。扫描仪不会读取二进制数据,它不是为此目的而设计的。扫描器期望提供一个实现 Readable 的对象 接口,其约定规定只能返回字符。它可以接受InputStream, 但是 API 声明使用底层平台的默认字符集将流中的字节转换为字符。

是否可以使用 Scanner 类读取二进制文件?如果是,那么如何?

根据前面的解释,这是不可能的,除非您以某种方式编写它们,以便上述转换字节的过程返回字符。如果您需要从流访问二进制数据,则需要避免使用 读者和可读对象。您需要处理原始 InputStreamsFilterInputStreams,将返回字节数组或合适的对象。在您的具体情况下,您需要 FileInputStream< /a>.

提示:

  1. 使用 Reader 和 在 Java 中处理字符时的 Writer 对象。
  2. 避免将上述内容用于二进制数据。请改用输入流和输出流。
  3. 了解装饰器模式是如何在 java.io 中实现的

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.
暗地喜欢 2024-11-21 23:04:08

您阅读了 API 文档吗?

一个简单的文本扫描器,可以解析
原始类型和字符串使用
正则表达式。

http://download.oracle.com/ javase/1,5.0/docs/api/java/util/Scanner.html

这可能对您有帮助:

使用 Java 读取结构化二进制文件的最佳方法

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文