POM*_*ATu 4 java android http file download
我正在尝试下载/恢复文件.恢复似乎工作,但整个下载带来了问题.执行此代码后,testfile为5242845.但它应该是5242880!我在十六进制编辑器中打开了这两个文件,并发现测试文件最后丢失了一些字节(开始没问题).这是代码:
String url = "http://download.thinkbroadband.com/5MB.zip";
String DESTINATION_PATH = "/sdcard/testfile";
URLConnection connection;
connection = (HttpURLConnection) url.openConnection();
File file = new File(DESTINATION_PATH);
if (file.exists()) {
downloaded = (int) file.length();
connection.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = (downloaded == 0) ? new FileOutputStream(DESTINATION_PATH) : new FileOutputStream(DESTINATION_PATH, true);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
int i = 0;
int lenghtOfFile = connection.getContentLength();
while ((x = in.read(data, 0, 1024)) != -1) {
i++;
bout.write(data, 0, x);
downloaded += x;
}
Run Code Online (Sandbox Code Playgroud)
我认为这个问题就在这里while ((x = in.read(data, 0, 1024)) != -1) {.
例如,我们有1030字节长的文件.第一次写入是好的,bout.write(data,0,1024);但下次while ((x = in.read(data, 0, 1024)) != -1) {获得-1,因为1030-1024 =剩下6个字节.我们正在尝试写1024字节!我知道不应该这样,但似乎就是我说的.我该怎么想这个?谢谢.
bout.flush();
Run Code Online (Sandbox Code Playgroud)
和/或
bout.close();
Run Code Online (Sandbox Code Playgroud)