部分下载文件将自动删除

时间:2018-05-08 06:09:30

标签: java android

我正在尝试下载pdf文件它工作得很好。但是在完成下载之前如果应用程序处于销毁状态,部分下载文件将自动删除。所以我可以再次开始下载。我已经使用过这个代码,但它无法正常工作

            if (!file.exists()) {
                try {
                    URL url = new URL(url_text.replace(" ", "%20"));
                    Log.e("tarikul", url + "");
                    HttpURLConnection c = (HttpURLConnection) 
                      url.openConnection();
                    c.setConnectTimeout(5000);
                    c.setRequestMethod("GET");
                    c.connect();
                    int lengthOfFile = c.getContentLength();
                    if (lengthOfFile == 0)

                        Log.e("tarikul", "File length: " + lengthOfFile);
                    if (c.getResponseCode() == HttpURLConnection.HTTP_OK) {

                        Constants.FILE_DOWNLOADING = true;
                        Log.e("tarikul", "HTTP OK");
                        int count;
                        InputStream inputFile = new 
                    BufferedInputStream(url.openStream(), 10 * 1024);
                        OutputStream outFile = new FileOutputStream(file);
                        Log.e("tarikul", "22");
                        byte data[] = new byte[1024];
                        long total = 0;
                        while ((count = inputFile.read(data)) != -1) {
                            total += count;
                            publishProgress("" + (int) ((total * 100) / 
                         lengthOfFile));
                            outFile.write(data, 0, count);
                        }
                        Log.i("TEST", "Length Of File: " +lengthOfFile + 
                  "\nTotal Downloaded: " +total);
                        if (lengthOfFile == total) {
                            Log.i("TEST", "Download Succeeded.");
                        }
                        outFile.flush();
                        outFile.close();
                        inputFile.close();


                    } else {
                        Log.i("TEST", "Response error.");
                    }
                    c.disconnect();
                } catch (Exception e) {
                    Log.e("hello", "" + e.getMessage());
                  if (file.exists()) {
                       file.delete();
                    }
                    Constants.FILE_DOWNLOADING = false;

`

1 个答案:

答案 0 :(得分:0)

实现此用途DOWNLOAD MANAGER。我也坚持不懈,但终于找到了解决我问题的方法。