我正在使用FileWriter,当我写各种大小(高达3MB)的大文件时,除了logcat中的这些消息外,它运行良好。
我看了一下FileUtils.java源代码,write函数不使用getThreadPool()接口(阅读器使用)。
作为一个测试,我想我应该调整文件编写器以使用可运行接口,并能够获得编译和执行的代码——不幸的是,logcat消息仍然显示。。。
到目前为止,我的盖帽时间在25毫秒到1200毫秒之间。我还没有进行任何认真的比较测试来确定这一变化是否真的有什么不同——我只是在寻找logcat消息的缺失。
下面的这些变化会有什么真正的不同吗?
这些信息是我应该担心的吗?
我的java非常基础,但以下是我在阅读器实现之后所做的更改。
else if (action.equals("write")) {
this.write(args.getString(0), args.getString(1), args.getInt(2), args.getBoolean(3), callbackContext);
}
/* this is the original code
else if (action.equals("write")) {
long fileSize = this.write(args.getString(0), args.getString(1), args.getInt(2), args.getBoolean(3));
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
}*/
在下面的写函数中。。。
public void write(String filename, final String data, final int offset, final boolean isBinary, final CallbackContext callbackContext) throws FileNotFoundException, IOException, NoModificationAllowedException {
if (filename.startsWith("content://")) {
throw new NoModificationAllowedException("Couldn't write to file given its content URI");
}
final String fname = FileHelper.getRealPath(filename, cordova);
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
Log.d(LOG_TAG, "Starting write");
try {
boolean append = false;
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes();
}
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
FileOutputStream out = new FileOutputStream(fname, append);
byte buff[] = new byte[rawData.length];
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
out.close();
Log.d(LOG_TAG, "Ending write");
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, rawData.length));
} catch (IOException e) {
Log.d(LOG_TAG, e.getLocalizedMessage());
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
}
}
});
}
是的,这些消息很重要,您应该使用后台线程执行复杂的任务,例如文件编写。这个问题的原因是这些任务阻塞了cordova,例如用户界面滞后。
如果您的下一步操作依赖于此任务的完成,我建议您使用回调方法。