简体   繁体   English

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

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

Following is a sample class showing how I put String into ByteBuffer. 以下是显示如何将String放入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. 我可以将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);
 }

}

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. 您应该始终编写write方法,以相同的顺序和格式在“ read”方法中写出需要阅读的内容。

Unless you have good reason to do so, its simpler to use DataInput/DataOutputStream which support writeUTF/readUTF. 除非有充分的理由,否则使用支持writeUTF / readUTF的DataInput / DataOutputStream会更简单。

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

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