gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:01:35 28 4
gpt4 key购买 nike

下面是一个示例类,展示了如何将 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 会更简单。

关于java - 如何使用 FileChannel 和 ByteBuffer 从文件中写入和读取 Java 对象中的字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13565359/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com