3

I have an problem . I try download a pdf file and save this file in my application folder. But when I try do this I have a error and file is not save...

This is my provider

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

I put this in manifest

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

I do this :

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

And I have : java.io.IOException: No such file or directory

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
kiki Kala2
  • 399
  • 5
  • 19

3 Answers3

0

Make sure you have added write external storage permission in your menifest.

or please reffer to how to save a downloaded file into internal storage in android?

Hope the link will help.

Kuldeep Rathee
  • 282
  • 2
  • 7
0

Try changing those two methods like that:

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

Also you might need to change

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

to

path="."
Mershel
  • 542
  • 1
  • 9
  • 17
  • Its probably saved in your application folder, if you want it to be visible from Documents directory you have to mark it as visible. If you are working on Android version < 10 this should work for you: https://stackoverflow.com/questions/4646913/android-how-to-use-mediascannerconnection-scanfile – Mershel Jan 13 '20 at 11:40
  • java.io.IOException: No such file or directory I have here : dwldsPath.createNewFile(); – kiki Kala2 Jan 13 '20 at 11:51
  • Use this `File dwldsPath = createImageFile(context,cardId);` – Mershel Jan 13 '20 at 11:58
  • But now I have E/DisplayData: openFd: java.io.FileNotFoundException: open failed: EACCES (Permission denied) – kiki Kala2 Jan 13 '20 at 12:07
  • have you changed path to `path="."` ? Stackoverflow is not about someone doing your job for you, if you have more problems with your code then try solving it yourself. – Mershel Jan 13 '20 at 12:15
  • Yes I change this – kiki Kala2 Jan 13 '20 at 12:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/205862/discussion-between-kiki-kala2-and-mershel). – kiki Kala2 Jan 13 '20 at 12:16
0

in xml/path.xml file:

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

add permission to AndroidManifest.xml:

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

add to application tag in 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>

MainActivity:

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

DownloadFileFromURL :

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

   }
hosein moradi
  • 444
  • 3
  • 7