0

Following is a sample class showing how I put String into ByteBuffer. I am able to write String to a file like this, but I am not sure how can I know the size of byte array to read the title back again when deserializing.

public class TestClass {

 private Long id;
 private String title;

 public void write (final ByteBuffer byteBuffer) {
  byteBuffer.putInt(title.length());
  byteBuffer.put(title.getBytes());
 }

 public static UpdateFeed read (final ByteBuffer byteBuffer) {

 final long id = byteBuffer.getLong();

 final int titleLength = byteBuffer.getInt();
 byte[] titleArr = new byte[titleLength];
 byteBuffer.get(titleArr);
 String title = new String(titleArr);
 System.out.println("Title :"+title);


  ????????????????
 return new TestClass(id,title);
 }

}
Amit Gill
  • 35
  • 1
  • 7
  • Why? ObjectInputStreams work best with FileInputStreams. There's little to be gained by using NIO channels and buffers except a lot of code complexity. Given serialization overheads you won't find it goes significantly faster if at all. – user207421 Nov 27 '12 at 03:40
  • Hi EJP, thanks for sharing your concern. Please have a look at this article, which inspired me to use NIO Channel & Buffer http://mechanical-sympathy.blogspot.in/2012/07/native-cc-like-performance-for-java.html Please share your concern in detail if possible. FYI, I am working on a project where I need to store huge number of updates from users, and performance is a key issue – Amit Gill Nov 27 '12 at 07:19
  • I've already 'shared my concern in detail'. If you're concerned about performance, the bottleneck here is serialization, not the I/O. If you have huge numbers etc use a database. – user207421 Nov 28 '12 at 01:14

1 Answers1

1

I suggest you write the length first, then you can read back exactly that many bytes. You should always write you write method to write out what you need to read in your "read" method, in the same order and format.

Unless you have good reason to do so, its simpler to use DataInput/DataOutputStream which support writeUTF/readUTF.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130