سؤال

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.

[1] http://wiki.python.org/moin/UsingPickle

هل كانت مفيدة؟

المحلول

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 using ByteBuffer.wrap.

Here's a minimal change to your code which does write the t into the file:

byte[] bytes = new byte[10];
ByteBuffer bbuf = ByteBuffer.wrap(bytes);
CharBuffer cbuf = bbuf.asCharBuffer();
cbuf.put("t");
FileOutputStream test = new FileOutputStream("somebytes");
test.write(bytes);
test.close();

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 and ObjectInputStream. 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.

نصائح أخرى

You can

seek(position)
b = read(length)

Then b will be an array of bytes of your length.

Sorry - on rereading you're looking for writing, not reading.

A simpler version of the same thing is.

byte[] bytes = new byte[10];
bytes[1] = 't';

FileOutputStream test = new FileOutputStream("somebytes");
test.write(bytes);
test.close();

There are plenty of examples on how to read/write byte[] from files on the web. try google.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top