문제

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

}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top