[英]Removing the opening and trailing characters from a stream
我有一個低級緩存機制,該機制從服務器接收json數組並將其緩存在文件中。
實際的緩存機制只是將大型流保存到文件中,而沒有意識到它是json。 因此,當我想通過將流聚合到另一個文件中來將流附加到現有文件高速緩存時,我得到的結果如下:
[{"id":3144,"created_at":"1322064201"}][{"id":3144,"created_at":"1322064201"}]
顯然我想要的是這樣的:
[{"id":3144,"created_at":"1322064201"},{"id":3144,"created_at":"1322064201"}]
什么是最有效的方法?
我已經調查FilterReader ,但看到我所知,所有我真正需要做的是去除最后一個字符]
現有的高速緩存和新內容的第一個char [
和增加,
我認為有可能比檢查每個字符一個更好的辦法在這些大溪流中。
對於上下文,我的代碼執行以下操作:
... 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;
}
}
處理時間慢得令人無法接受,因此我正在尋找另一種選擇。 我正在考慮使用文件大小來確定文件的大小,並以這種方式刪除尾方括號
這種方法成功了
/**
* Copys the input streams in order to the output stream and retains json array
* format
*
* @param inputStreamA
* @param inputStreamB
* @param outputStream
* @throws IOException
*/
private void copyStreamsToOutput(InputStream inputStreamA, InputStream inputStreamB,
FileOutputStream outputStream) throws IOException {
copyStream(inputStreamA, outputStream);
// truncate file to remove trailing ']'
outputStream.getChannel().truncate(outputStream.getChannel().size() - 1);
// add comma between json objects
outputStream.write(COMMA);
// skip '['
inputStreamB.skip(1);
// and copy rest of streamas normal
copyStream(inputStreamB, outputStream);
}
如果這是一種不好的做法,將對這里非常感興趣,我猜可能存在編碼問題。
更新
/**
* Copys the input streams in order to output stream and retains json array
* format
*
* @param inputStreamA
* @param inputStreamB
* @param outputStream
* @throws IOException
*/
private void copyStreamsToOutput(InputStream inputStreamA, InputStream inputStreamB,
FileOutputStream outputStream) throws IOException {
copyStream(inputStreamA, outputStream);
long channelSize = outputStream.getChannel().size();
// truncate file to remove trailing ']'
outputStream.getChannel().truncate(channelSize - 1);
// check to see if array was empty (2 = [])
if (channelSize > 2) {
// add comma between json objects
outputStream.write(COMMA);
}
// skip '['
inputStreamB.skip(1);
// and copy rest of streams normal
copyStream(inputStreamB, outputStream);
long newChannelSize = outputStream.getChannel().size();
// check if we haven't just added a empty array
if(newChannelSize - channelSize < 2){
// if so truncate to remove comma
outputStream.getChannel().truncate(channelSize - 1);
outputStream.write(CLOSE_SQUARE_BRACKET);
}
}
增加了處理任一流中的空json數組的功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.