【问题标题】:How to delete a pdf if download was incomplete in android?如果在android中下载不完整,如何删除pdf?
【发布时间】:2016-08-04 13:07:31
【问题描述】:

我正在从我的服务器下载一个 pdf 文件。最近我遇到了 当我的互联网在下载过程中断开时,我 无法打开 pdf 文件,因为它不完整。如何删除 如果下载不完整并且文件包含 该扩展程序已在此过程中保存?这是我的代码 当前用于从服务器下载 pdf。

class DownloadFileAsync extends AsyncTask<String, String, String>
{
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
    final int notify_id = 1;
    final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

    private String resp;

    @Override
    protected String doInBackground(String... params) {


        int count;
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("Download Status...");
        builder.setContentText("Download in Progress...");
        try {
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            connection.connect();

            int lengthOfFile = connection.getContentLength();
            Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);

            String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
            Log.d("FILENAME", fileName);
            resp = fileName;

            if (isSDPresent) {

                InputStream inputStream = new BufferedInputStream(url.openStream());
                OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = inputStream.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lengthOfFile));
                    outputStream.write(data, 0, count);
                }

                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                InputStream inputStream = new BufferedInputStream(url.openStream());
                OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = inputStream.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lengthOfFile));
                    outputStream.write(data, 0, count);
                }

                outputStream.flush();
                outputStream.close();
                inputStream.close();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return params[0];
    }

    @Override
    protected void onPostExecute(String filename) {
        Log.d("PARAM", filename);

        String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());

        int position = Arrays.asList(pdf_url).indexOf(filename);
        Log.d("Position",String.valueOf(position));
        String magazine_id = magazine_names[position];

        if (isSDPresent) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            builder.setProgress(0, 0, false);
            builder.setContentText("Download Complete...");
            NM.notify(notify_id, builder.build());

            TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            String device_imei = telephonyManager.getDeviceId();
            update_info(device_imei,magazine_id);
            Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);

            Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.setAction(Intent.ACTION_VIEW);

            intent.setData(uri);

            startActivity(intent);

        } else {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            builder.setProgress(0, 0, false);
            builder.setContentText("Download Complete...");
            NM.notify(notify_id, builder.build());

            Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);

            Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.setAction(Intent.ACTION_VIEW);

            intent.setData(uri);

            startActivity(intent);

        }


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected void onProgressUpdate(String... values) {
        Log.d("ANDRO_ASYNC", values[0]);
        progressDialog.setProgress(Integer.parseInt(values[0]));
        builder.setProgress(100, Integer.parseInt(values[0]), false);
        NM.notify(notify_id, builder.build());
    }
}

感谢任何帮助或建议。谢谢。

【问题讨论】:

  • 感谢@PaoloForgia 的编辑,您能提供解决方案吗?
  • file.delete() 呢?
  • 有没有办法查出是下载不完整还是java中保存了不完整的文件。所以根据这个条件我可以删除文件。
  • 比较下载文件的文件长度和预期长度。或删除文件以防下载未完成(进度条未达到 100%)

标签: java android pdf download


【解决方案1】:

你可以得到一个指向文件的指针并使用“delete()”方法

String fileName = "my_file"; //your file name
File parentFile; //get your parent file 
File myFile = new File(parentFile, fileName);
myFile.delete();

【讨论】:

  • 谢谢。有没有办法查明下载是否不完整或java中保存的文件不完整。所以基于这种情况,我可以删除现有代码中的文件。
  • 而不是这样做:return params[0];只需将变量 StringToReturnToPostExecute 设置为 null,直到下载结束,如果下载成功,您将在其中将其设置为 params[0]。然后在你的 onPostExecute 方法中,如果接收到的参数为 null,你就会知道出了点问题,然后你就删除文件
  • 有趣的问题,你的代码的问题是很多可能会出错我从来没有想过如何处理大文件下载任务但想到以下情况 - wifi/3g 关闭,没有接收,服务器已关闭等..)。现在您需要考虑每种情况下的结果是什么,以便简化事情,我建议检查下载开始时的文件大小和下载结束时的文件大小(调用 onPostExcute 时)。
  • 您可以使用 - int length = inputStream.available(); 来检查输入流大小(以字节为单位)并将其与 myFile.length(),注意输入流avaibevle函数返回int,文件长度函数返回long
  • 我可以给你的最后一个建议,在你让它工作并且你了解如何处理文件和流之后,删除你的代码并使用 REST api 重新编写它(即改造,okhttpclient,Android 异步 Http 客户端, ETC..)。图像使用滑翔,或毕加索。
【解决方案2】:
  1. 您可以先处理网络 I/O 异常,而不是捕获“异常”。

    //网络超时抛出异常

    catch (InterruptedIOException iioe) { System.err.println("读操作时远程主机超时"); }

    //发生一般网络I/O错误时抛出异常

    catch (IOException ioe) { System.err.println("网络I/O异常-" + ioe); } 那么

    catch(Exception e) {System.err.println("Exception -" + ioe); }

  2. 当您收到网络类型错误时,您可以检查该文件是否已创建/存在,然后您可以使用以下代码将其删除,

    文件 fdelete = new File(uri.getPath()); 如果(fdelete.exists()){ 如果(fdelete.delete()){ System.out.println("文件已删除:" + uri.getPath()); } 别的 { System.out.println("文件未删除:" + uri.getPath()); } }

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    根据我完成的 Roee 回答,这里应该是一个工作示例:

    class DownloadFileAsync extends AsyncTask<String, String, String> {
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
        final int notify_id = 1;
        final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    
        private String resp;
    
        @Override
        protected String doInBackground(String... params) {
    
    
            int count;
    
            String stringToReturnToPostExecute = null;
    
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle("Download Status...");
            builder.setContentText("Download in Progress...");
            try {
                URL url = new URL(params[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
    
                int lengthOfFile = connection.getContentLength();
                Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
    
                String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
                Log.d("FILENAME", fileName);
                resp = fileName;
    
                if (isSDPresent) {
    
                    InputStream inputStream = new BufferedInputStream(url.openStream());
                    OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = inputStream.read(data)) != -1) {
                        total += count;
                        publishProgress("" + (int) ((total * 100) / lengthOfFile));
                        outputStream.write(data, 0, count);
                    }
    
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                } else {
                    InputStream inputStream = new BufferedInputStream(url.openStream());
                    OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = inputStream.read(data)) != -1) {
                        total += count;
                        publishProgress("" + (int) ((total * 100) / lengthOfFile));
                        outputStream.write(data, 0, count);
                    }
    
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    stringToReturnToPostExecute = params[0];
                }
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringToReturnToPostExecute ;
        }
    
        @Override
        protected void onPostExecute(String filename) {
            Log.d("PARAM", filename);
    
            if(filename == null) {
               //TODO delete your file here and dismissthe Dialog as well
            }
            String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
    
            int position = Arrays.asList(pdf_url).indexOf(filename);
            Log.d("Position",String.valueOf(position));
            String magazine_id = magazine_names[position];
    
            if (isSDPresent) {
                dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                builder.setProgress(0, 0, false);
                builder.setContentText("Download Complete...");
                NM.notify(notify_id, builder.build());
    
                TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                String device_imei = telephonyManager.getDeviceId();
                update_info(device_imei,magazine_id);
                Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
    
                Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
                intent.setAction(Intent.ACTION_VIEW);
    
                intent.setData(uri);
    
                startActivity(intent);
    
            } else {
                dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                builder.setProgress(0, 0, false);
                builder.setContentText("Download Complete...");
                NM.notify(notify_id, builder.build());
    
                Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
    
                Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
                intent.setAction(Intent.ACTION_VIEW);
    
                intent.setData(uri);
    
                startActivity(intent);
    
            }
    
    
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    
        @Override
        protected void onProgressUpdate(String... values) {
            Log.d("ANDRO_ASYNC", values[0]);
            progressDialog.setProgress(Integer.parseInt(values[0]));
            builder.setProgress(100, Integer.parseInt(values[0]), false);
            NM.notify(notify_id, builder.build());
        } }
    

    【讨论】:

      【解决方案4】:
      class DownloadFileAsync extends AsyncTask<String, String, String>
      {
          final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
          final int notify_id = 1;
          final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
      
          private String resp;
          int lengthOfFile;
      
          @Override
          protected String doInBackground(String... params) {
      
      
              int count;
              builder.setSmallIcon(R.mipmap.ic_launcher);
              builder.setContentTitle("Download Status...");
              builder.setContentText("Download in Progress...");
              try {
                  URL url = new URL(params[0]);
                  URLConnection connection = url.openConnection();
                  connection.connect();
      
                  lengthOfFile = connection.getContentLength();
                  Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
      
                  String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
                  Log.d("FILENAME", fileName);
                  resp = fileName;
      
                  if (isSDPresent) {
      
                      InputStream inputStream = new BufferedInputStream(url.openStream());
                      OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
                      byte data[] = new byte[1024];
                      long total = 0;
                      while ((count = inputStream.read(data)) != -1) {
                          total += count;
                          publishProgress("" + (int) ((total * 100) / lengthOfFile));
                          outputStream.write(data, 0, count);
                      }
      
                      outputStream.flush();
                      outputStream.close();
                      inputStream.close();
                  } else {
                      InputStream inputStream = new BufferedInputStream(url.openStream());
                      OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
                      byte data[] = new byte[1024];
                      long total = 0;
                      while ((count = inputStream.read(data)) != -1) {
                          total += count;
                          publishProgress("" + (int) ((total * 100) / lengthOfFile));
                          outputStream.write(data, 0, count);
                      }
      
                      outputStream.flush();
                      outputStream.close();
                      inputStream.close();
      
                  }
      
      
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return params[0];
          }
      
          @Override
          protected void onPostExecute(String filename) {
              Log.d("PARAM", filename);
      
              String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
      
              Log.d("LENGTH OF FILE : ",String.valueOf(lengthOfFile));
      
              int position = Arrays.asList(pdf_url).indexOf(filename);
              Log.d("Position",String.valueOf(position));
              String magazine_id = magazine_names[position];
      
              if (isSDPresent) {
      
                  File f = new File("/storage/emulated/0/shatayushi/" +fname);
                  if (f.length()<lengthOfFile)
                  {
                      if (f.delete())
                      {
                          progressDialog.setProgress(0);
                          dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                          builder.setProgress(0, 0, false);
                          builder.setContentText("Download was interrupted please try again!");
                          NM.notify(notify_id, builder.build());
                          Toast.makeText(MainActivity.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
                          Log.d("Del","File deleted");
                      }else
                      {
                          Toast.makeText(MainActivity.this, "File not deleted", Toast.LENGTH_SHORT).show();
                          Log.d("NOTDel","File not deleted");
                      }
                  }else {
                      progressDialog.setProgress(0);
                      dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                      builder.setProgress(0, 0, false);
                      builder.setContentText("Download Complete...");
                      NM.notify(notify_id, builder.build());
      
                      TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                      String device_imei = telephonyManager.getDeviceId();
                      // update_info(device_imei,magazine_id);
      
                      dbHandler.updateDownloadStatus(magazine_id, "YES");
                      Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
      
                      Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
                      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      
                      intent.setAction(Intent.ACTION_VIEW);
      
                      intent.setData(uri);
      
                      startActivity(intent);
                  }
      
              } else {
      
                  File f = new File("/storage/emulated/0/shatayushi/" +fname);
                  if (f.length()<lengthOfFile)
                  {
                      if (f.delete())
                      {
                          progressDialog.setProgress(0);
                          dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                          builder.setProgress(0, 0, false);
                          builder.setContentText("Download was interrupted please try again!");
                          NM.notify(notify_id, builder.build());
                          Toast.makeText(MainActivity.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
                          Log.d("Del","File deleted");
                      }else
                      {
                          Toast.makeText(MainActivity.this, "File not deleted", Toast.LENGTH_SHORT).show();
                          Log.d("NOTDel","File not deleted");
                      }
                  }else
                  {
                      dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
                      builder.setProgress(0, 0, false);
                      builder.setContentText("Download Complete...");
                      NM.notify(notify_id, builder.build());
      
                      Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
      
                      Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
                      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      
                      intent.setAction(Intent.ACTION_VIEW);
      
                      intent.setData(uri);
      
                      startActivity(intent);
                  }
      
      
              }
      
      
          }
      
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              showDialog(DIALOG_DOWNLOAD_PROGRESS);
          }
      
          @Override
          protected void onProgressUpdate(String... values) {
              Log.d("ANDRO_ASYNC", values[0]);
              progressDialog.setProgress(Integer.parseInt(values[0]));
              builder.setProgress(100, Integer.parseInt(values[0]), false);
              NM.notify(notify_id, builder.build());
          }
      }
      

      我终于明白了对不起@Rotwang,谢谢@user3793589。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-16
        • 2022-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多