![](/img/trans.png)
[英]How to write double into file, using filechannel and bytebuffer?
[英]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.