繁体   English   中英

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

[英]How to write and read a string property in a Java Object from a file with FileChannel and ByteBuffer

以下是显示如何将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);
 }

}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM