[英]My Java code downloads a file, but it's the wrong size
The following code creates a file, but it is not openable, and the file size it creates does not remotely correspond with the size of the file I am trying to download. 以下代码创建了一个文件,但是它无法打开,并且它创建的文件大小与我要下载的文件的大小没有远程对应。 (using whatsapp updater link as an example): (以whatsapp更新程序链接为例):
private static boolean download(){
try {
String outfile = "/sdcard/whatsapp.apk";
URL download = new URL("https://www.whatsapp.com/android/current/WhatsApp.apk");
ReadableByteChannel rbc = Channels.newChannel(download.openStream());
FileOutputStream fileOut = new FileOutputStream(outfile);
fileOut.getChannel().transferFrom(rbc, 0, 1 << 24);
fileOut.close();
rbc.close();
return true;
} catch (IOException ioe){
return false;
}
}
EDIT: this is a shortened version of my full code, (the full code alows network ops on main thread, and trust all certificates), also changed the code in the question. 编辑:这是我完整代码的简化版本,(完整代码允许主线程执行网络操作,并信任所有证书),也更改了问题中的代码。
Tests show that IOException is not being throw, and code completes without error. 测试表明没有抛出IOException,并且代码完整无误。 so, Why is the downloaded file not usable? 那么,为什么下载的文件不可用?
Fewer than the requested number of bytes will be transferred if the source channel has fewer than count bytes remaining, or if the source channel is non-blocking and has fewer than count bytes immediately available in its input buffer. 如果源通道的剩余剩余字节数少于计数字节,或者源通道是非阻塞的且输入缓冲区中立即可用的计数字节数少于字节,则将传输少于请求的字节数。
This means that it is not guaranteed that this will save the entire file at once. 这意味着不能保证这将一次保存整个文件。 You should put this call in a loop which breaks once the entire download has completed. 您应该将此调用置于一个循环中,一旦完成整个下载,该循环就会中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.