Question

So my program works like this: It downloads a .txt file from the dropbox and saves it to downloads directory.

Uri uri = Uri.parse(file);
DownloadManager.Request r = new DownloadManager.Request(uri);

// This put the download in the same Download dir the browser uses
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "upload");

r.allowScanningByMediaScanner();

// Start download
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(r);

And the code is working fine, it downloads the file called upload.txt. So now i want to read from it. I have been looking for some codes and nothing seems to be working...
Here is my current code, it throws a FileNotFoundException but file is located there.
Any tips?

String text="";
    FileInputStream Fin=new FileInputStream(Environment.DIRECTORY_DOWNLOADS+"upload");
    byte[] b=new byte[100];
    Fin.read(b);
    text=new String(b);
    Fin.close();

Ofc i have tried putting "upload.txt", and even "/upload" and "/upload.txt" but still nothing.
If anyone can give me code that reads a text file, it would be awesome, or if someone could give me a code that can get the source code form a html site ( without JSOUP and other parsers, i have tried that, i want to implement my own parser ). Thanks!!

Was it helpful?

Solution

Change

FileInputStream Fin=new FileInputStream(Environment.DIRECTORY_DOWNLOADS+"upload");

to

FileInputStream Fin=new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "upload"));

You should use Environment.getExternalStoragePublicDirectory to get the path.


Or if you like more,

FileInputStream Fin=new FileInputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/upload");

Change

r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "upload");

too with

r.setDestinationInExternalPublicDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "upload");

OTHER TIPS

Took me ages, but finally: You should add to the manifest the various permissions (android.permission.READ_EXTERNAL_STORAGE...)

But this is not enough! you should explicitly ask for these permissions in the onCreate():

requestPermissions({android.permission.READ_EXTERNAL_STORAGE,...}, 200);

Only afterwards you can access these directories.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top