如何使用FileChannel和ByteBuffer从文件中编写和读取Java对象中的字符串属性

时间:2012-11-26 12:59:55

标签: java serialization nio bytebuffer filechannel

以下是一个示例类,展示了如何将String放入ByteBuffer。我能够将String写入这样的文件,但是我不知道在反序列化时我怎么能知道字节数组的大小才能重新读取标题。

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

}

1 个答案:

答案 0 :(得分:1)

我建议你先编写长度,然后你就可以准确地读回那么多字节了。您应该始终以write方法编写方法,以相同的顺序和格式在“读取”方法中写出您需要阅读的内容。

除非你有充分的理由这样做,否则使用支持writeUTF / readUTF的DataInput / DataOutputStream更简单。

相关问题