【发布时间】:2017-10-02 01:02:40
【问题描述】:
我有一个术语的 HashMap,其中包含单词出现的页面、页面中单词的频率以及它们的位置的数据。
例如:单词 - [页码、页面中的词频、页面中的位置]
cat [1, 3, 1, 2, 5 ], [2, 2, 2, 5 ]
dog [2, 2, 1, 7 ]
如何将这些信息存储在易于读取的二进制文件中?
我做了以下尝试:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for(String word: invertedIndex.keySet()) {
out.writeUTF(word); // Write the word
for(Entry entry: invertedIndex.get(word)) { // Info for a page
out.writeInt(entry.pageNum); // Write its page number
out.writeInt(entry.wordFrequency); // Write its freq in that page
for(int position: entry.positions) {
out.writeInt(position); // Write the positions
}
}
}
byte[] bytes = baos.toByteArray();
FileOutputStream fos = new FileOutputStream(PATH);
fos.write(bytes);
fos.close();
不确定这是否正确...在此先感谢。
编辑:谢谢,原来我的问题更多是关于如何解码这个相当严格的编码。
【问题讨论】:
-
为什么不直接序列化
Map,即使用ObjectOutputStream? -
@Andreas 这是一个任务,并被告知“不要简单地将序列化的 java 对象写入磁盘”。有没有办法以二进制形式保存这种数据结构?
-
“有没有办法保存这个数据结构?” 是的……你写代码。你已经编写了代码。您的实际问题是什么?
-
可能是你的老师在你连载之前找你compress?
-
@StephenC - 如何将这些数据写入二进制文件,以便轻松读取数据?像 [猫 1 3 1 2 5 2 2 2 5 狗 2 2 1 7]。如何将其存储在我读取它并知道某些字节(?)是字符串的二进制文件中?
标签: java binary binaryfiles binary-data