开发者

file never fully downloaded

I am trying to download/resume file. Resume seems to work, but whole download brings the problem. After executing this code testfile is 5242845. But it should be 5242880! I opened this two files in the hex editor and figured out that testfile missing some bytes at the end (begining is okay). This is the code:

                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;
         }

I think that the problem is here while ((x = in.read(data, 0, 1024)) != -1) {.

For example we have file 1030 bytes long. First write is good, bout.write(data,0,1024); but next time while ((x = in.read(data, 0, 1024)) != -1) { gets -1, because 1030-1024=6 bytes left. And we are trying to write 1024 bytes! I know it should not be so, but it seems that it is how I said. How can I figure this? Thanks.


bout.flush();

and/or

bout.close();


You need to close your BufferedOutputStream to ensure that all that is buffered is sent to the buffered OutputStream.


google told me, there is a "available" method of bufferedinputstream, so you can write like (I´m not an java guru)

while (in.available() > 0) 
{
    x = in.read(data, 0, 1024);
    bout.write(data, 0, x);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜