【发布时间】:2012-01-04 22:55:38
【问题描述】:
我有一个低级缓存机制,它从服务器接收一个 json 数组并将其缓存在一个文件中。
实际的缓存机制只是将 large 流保存到文件中,而不知道它是 json。因此,当我想通过将流聚合到另一个文件中来将流附加到现有文件缓存时,我最终会得到这样的结果:
[{"id":3144,"created_at":"1322064201"}][{"id":3144,"created_at":"1322064201"}]
显然我想要的是这样的:
[{"id":3144,"created_at":"1322064201"},{"id":3144,"created_at":"1322064201"}]
最有效/最有效的方法是什么?
我查看了FilterReader,但据我所知,我真正需要做的就是删除现有缓存的最后一个字符] 和新内容[ 的第一个字符并添加一个, I认为可能有比检查这些大流中的每个字符更好的方法。
对于上下文,我的代码执行如下操作:
... input stream passed with new content
File newCache = new File("JamesBluntHatersClub")
FileOutputStream tempFileOutputStream = new FileOutputStream(newCache);
FileInputStream fileInputStream = new FileInputStream(existingCache);
copyStream(fileInputStream, tempFileOutputStream);
copyStream(inputStream, tempFileOutputStream);
... clean up
更新:
已经实现了一个FilterReader,它一次检查一个字符,如下所示:
@Override
public int read() throws IOException {
int content = super.read();
// replace open square brackets with comma
switch (content) {
case SQUARE_BRACKETS_OPEN:
return super.read();
case SQUARE_BRACKETS_CLOSE:
return super.read();
default:
return content;
}
}
处理时间慢得令人无法接受,所以我正在寻找另一种选择。我正在考虑使用文件大小来确定文件的大小并以这种方式删除尾部方括号
【问题讨论】:
标签: java json file caching stream