从文件中写入和读取 byte[]
我正在寻找一些简单的东西(最好没有外部库)来从文件中写入和加载 byte[] 。或多或少有点像[Python的pickle][1]。
byte[] bytes = new byte[10];
ByteBuffer bbuf = new ByteBuffer.allocate(bytes.length);
bbuf.wrap(bytes); // edited due to Jon Skeet's answer
CharBuffer cbuf = bbuf.asCharBuffer();
cbuf.put("t");
FileOutputStream test = new FileOutputStream("somebytes");
test.write(bytes);
test.close();
问题似乎是我无法从这样的文件中读取对象结构。此外,在十六进制编辑器中,文件“somebytes”仅包含几个或 0。因此,FileOutputStream 似乎没有将任何内容(“t”或字节等效项)放入其中。
I'm looking for something simple (no external lib preferably) to write and load a byte[] from a file. More or less something like [Python's pickle][1].
byte[] bytes = new byte[10];
ByteBuffer bbuf = new ByteBuffer.allocate(bytes.length);
bbuf.wrap(bytes); // edited due to Jon Skeet's answer
CharBuffer cbuf = bbuf.asCharBuffer();
cbuf.put("t");
FileOutputStream test = new FileOutputStream("somebytes");
test.write(bytes);
test.close();
The problem seems to be that I cannot read the Object structure from a file like that. In a hex-editor furthermore the file "somebytes" contains just a couple or 0s. So it doesn't seem the FileOutputStream puts any of the content ("t" or the byte-equivalent) into it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已经分配了一个大小为
字节
的字节缓冲区,但这并不意味着该字节缓冲区与字节数组关联。您可以使用 ByteBuffer.wrap 包装字节数组。以下是对代码的最小更改,确实将
t
写入文件中:请注意,对于实际代码,您应该使用 try/finally 块来确保文件始终是无论是否有例外情况均关闭。
然而,这距离序列化还有很长的路要走。 Java确实有自己的二进制序列化 - 请参阅
ObjectOutputStream
和ObjectInputStream
。然而,就我个人而言,我通常会避免这种序列化,因为面对类的更改,它可能非常脆弱。还有各种其他序列化方法,例如使用 Thrift 或 Protocol Buffers 进行二进制序列化,或者序列化为 XML、JSON 或其他一些人类可读的格式。You've allocated a byte buffer with the size of
bytes
, but that doesn't mean the byte buffer is associated with the byte array. You can wrap a byte array usingByteBuffer.wrap
.Here's a minimal change to your code which does write the
t
into the file:Note that for real code you should use a try/finally block to make sure the file is always closed regardless of exceptions.
However, this is a long way from serialization. Java does have its own binary serialization - see
ObjectOutputStream
andObjectInputStream
. Personally I usually avoid this sort of serialization however, as it can be very brittle in the face of changes to classes. There are various other approaches to serialization, such as using Thrift or Protocol Buffers for binary serialization, or serializing to XML, JSON or some other human-readable format.你可以
然后 b 将是你长度的字节数组。
抱歉——重读时你是在寻找写作,而不是阅读。
You can
Then b will be an array of bytes of your length.
Sorry - on rereading you're looking for writing, not reading.
同一件事的一个更简单的版本是。
网上有很多关于如何从文件中读取/写入 byte[] 的示例。尝试谷歌。
A simpler version of the same thing is.
There are plenty of examples on how to read/write byte[] from files on the web. try google.