在阅读here并使用JsonWriter和JsonReader创建要发送和接收的大型Object时。我想跟踪发送的总字节数。
答案 0 :(得分:2)
JsonWriter
或JsonReader
中没有任何内容可以为您提供。
真正唯一的方法是将您当前传递的Reader
或Writer
换行/延伸到JsonReader
/ JsonWriter
并跟踪正在读/写的字节数。
编辑添加:例如,您可以执行以下操作:
class MyWriterWrapper extends Writer {
private Writer realWriter;
private int bytesWritten;
public MyWriterWrapper(Writer realWriter) {
super();
this.realWriter = realWriter;
}
public int getBytesWritten() {
return bytesWritten;
}
@Override
public Writer append(CharSequence csq) throws IOException {
realWriter.append(csq);
bytesWritten += csq.length();
return this;
}
// Implement/Override all other Writer methods the same way
}
如果Writer
是一个界面,那会更清洁但是......呃,你能做什么。如果您知道自己只会使用一种Writer
(例如,BufferedWriter
),那么可以扩展它,覆盖所有方法并重新调用this
上的方法而不是通过构造函数传入的私有realWriter
实例。
答案 1 :(得分:0)
没有从JsonReader获取接收字节数的默认方法。我写了一篇有点棘手的Hack,下面提到了:
从inputstream读取字节并将其写入内部存储文件
while ((count = inputStream.read(data)) != -1) { total += count; final long downloadedLength = total; final long totalLength = lengthOfData; **// Here you get the size of bytes received** outStream.write(data, 0, count); }
关闭所有打开的流(上面创建的输入和输出流)
打开新创建的文件的输入流
InputStream stream = mContext.openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(stream);
现在您有一个JsonReader
让JsonReader使用此输入流来解析数据
解析完成后,删除为临时使用而创建的文件
InputStream stream = mContext.openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(stream);
jsonReader = 新的JsonReader(inputStreamReader);
parseMyJSON(jsonReader);文件文件=新文件(mContext.getFilesDir(),FILE_NAME);
file.delete();
答案 2 :(得分:0)
No way. Even if you wrap your input stream in some kind of wrapper to count bytes (e. g. apache's CountingInputStream), the results will be incorrect because of JsonReader's internal buffering. I've experimented with ~300 bytes long JSONs. CountingInputStream reported that ~4kb was read each time.