【问题标题】:Downloading and saving a file下载和保存文件
【发布时间】:2020-01-13 19:28:55
【问题描述】:

我有一个问题。我尝试下载一个 pdf 文件并将此文件保存在我的应用程序文件夹中。但是当我尝试这样做时,我有一个错误并且文件没有保存......

这是我的提供者

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="Android/data/xxx/files/Download" />
</paths>

我把它放在清单中

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="xxx.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths2" />
    </provider>

我这样做:

    public static void parseBase64ToPDFAndNoOpen(String base64, String cardId ,Context context) throws IOException {

        FileOutputStream os;
        String path;
        Uri photoURI = null;
        try {
            photoURI = FileProvider.getUriForFile(context.getApplicationContext(),
                    BuildConfig.APPLICATION_ID + ".provider", createImageFile(context,cardId));
        } catch (IOException e) {
            e.printStackTrace();
        }
        File dwldsPath = new File(photoURI.toString());
//            File dwldsPath = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + cardId + ".pdf");
        if (!dwldsPath.exists()) {
            dwldsPath.createNewFile();
            byte[] pdfAsBytes = Base64.decode(base64, 0);
            os = new FileOutputStream(dwldsPath, false);
            os.write(pdfAsBytes);
            os.flush();
            os.close();
        }
    }

private static File createImageFile(Context context,String name) throws IOException {
   File imagesDir = new File(getDefaultTempFilesPath(context));
    return File.createTempFile(
            name, /* prefix */
            ".pdf", /* suffix */
            imagesDir /* directory */
    );
}




   private static String getDefaultTempFilesPath(Context context) {
        if (context != null) {
            File f = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            if (f != null)
                return f.getPath();
            else {
                f = context.getFilesDir();
                if (f != null)
                    return f.getPath();
            }
        }
        return null;
    }

我有:java.io.IOException: 没有这样的文件或目录

【问题讨论】:

    标签: java android


    【解决方案1】:

    确保您已在清单中添加写入外部存储权限。

    或请参考how to save a downloaded file into internal storage in android?

    希望链接对您有所帮助。

    【讨论】:

      【解决方案2】:

      尝试像这样更改这两种方法:

      private static File createImageFile(Context context, String name) {
          return new File(getDefaultTempFilesPath(context), name + ".pdf");
      }
      
      private static File getDefaultTempFilesPath(Context context) {
          File f = null;
          if (context != null) {
              f = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
              if (f == null)
                  f = context.getFilesDir();
          }
          return f;
      }
      

      另外你可能需要改变

      path="Android/data/xxx/files/Download"
      

      path="."
      

      【讨论】:

      • 它可能保存在您的应用程序文件夹中,如果您希望它在 Documents 目录中可见,则必须将其标记为可见。如果您使用的是 Android 版本 stackoverflow.com/questions/4646913/…
      • java.io.IOException: 我这里没有这样的文件或目录:dwldsPath.createNewFile();
      • 使用这个File dwldsPath = createImageFile(context,cardId);
      • 但是现在我有 E/DisplayData: openFd: java.io.FileNotFoundException: open failed: EACCES (Permission denied)
      • 您是否已将路径更改为 path="." ? Stackoverflow 并不是要有人为您完成工作,如果您的代码有更多问题,请尝试自己解决。
      【解决方案3】:

      在 xml/path.xml 文件中:

      <paths xmlns:android="http://schemas.android.com/apk/res/android">
      <external-path
          name="external_files"
          path="." />
      </paths>
      

      为 AndroidManifest.xml 添加权限:

         <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      

      添加到 AndroidManifest.xml 中的应用程序标签:

              <provider
              android:name=".Modules.ContentProviders"
              android:authorities="${applicationId}.provider"
              android:exported="true"
              android:grantUriPermissions="true">
              <meta-data
                  android:name="android.support.FILE_PROVIDER_PATHS"
                  android:resource="@xml/path" />
          </provider>
      

      主活动:

      DownloadFileFromURL sdsa = new DownloadFileFromURL();
      sdsa.execute(downloadurl);
      

      从 URL 下载文件:

        class DownloadFileFromURL extends AsyncTask<String, String, String> {
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              showDialog(progress_bar_type);
      
          }
      
          @Override
          protected String doInBackground(String... f_url) {
              int count;
              try {
      
                  URL as = new URL(f_url[0]);
                  URLConnection conection = as.openConnection();
                  conection.connect();
                  int lenghtOfFile = conection.getContentLength();
                  InputStream input = new BufferedInputStream(as.openStream(), 8192);
                  String diskurl = as.toString().replace(Constants.Download_url, "");
                  String diskurlSpace = diskurl.replaceAll("%20", " ");
                  OutputStream output = new 
                  FileOutputStream(Environment.getExternalStorageDirectory() + 
                   "/DocManager" + diskurlSpace);
                  byte data[] = new byte[1024];
                  long total = 0;
                  while ((count = input.read(data)) != -1) {
                      total += count;
                      publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                      output.write(data, 0, count);
                  }
                  output.flush();
                  output.close();
                  input.close();
              } catch (Exception e) {
                  Log.e("Error: ", e.getMessage());
              }
              return null;
          }
      
          protected void onProgressUpdate(String... progress) {
              pDialog.setProgress(Integer.parseInt(progress[0]));
          }
      
          @Override
          protected void onPostExecute(String file_url) {
              dismissDialog(progress_bar_type);
              Snackbar.make(rayMain, "download and saved", 
           Snackbar.LENGTH_LONG).show();
          }
      
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多