java中Scanner类的问题
我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要读取二进制文件,您可以将 DataInputStream 或 ByteBuffer 与 NIO 结合使用。
To read a binary file you can use DataInputStream or ByteBuffer with NIO.
这是一个正确的观察。扫描仪不会读取二进制数据,它不是为此目的而设计的。扫描器期望提供一个实现 Readable 的对象 接口,其约定规定只能返回字符。它可以接受InputStream, 但是 API 声明:使用底层平台的默认字符集将流中的字节转换为字符。
根据前面的解释,这是不可能的,除非您以某种方式编写它们,以便上述转换字节的过程返回字符。如果您需要从流访问二进制数据,则需要避免使用 读者和可读对象。您需要处理原始 InputStreams 或 FilterInputStreams,将返回字节数组或合适的对象。在您的具体情况下,您需要 FileInputStream< /a>.
提示:
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.
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:
您阅读了 API 文档吗?
http://download.oracle.com/ javase/1,5.0/docs/api/java/util/Scanner.html
这可能对您有帮助:
使用 Java 读取结构化二进制文件的最佳方法
Did you read the API docs ?
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