簡體   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