Read Downloaded Text File - Android - android

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

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");

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.

Related

Check if file exist inside custom folder in Downloads - getExternalStoragePublicDirectory deprecated

What I'm trying to achieve is to check before download if the file exists so i don't have to re-download it again. For example, i have to open for the first time this pdf from the Internet "history-of-comics.pdf", in order to do so i have to download it and open inside my app, the second time i choose to re-read it, i have to be sure that "history-of-comics.pdf" if exists inside Downloads/MyDocs, i don't have to waste resources and let the user wait to download it again. Currently the app targetSdkVersion is 29 and what i have done so far is:
Give permissions for READ_EXTERNAL_STORAGE & WRITE_EXTERNAL_STORAGE
Included in manifest android:requestLegacyExternalStorage="true" inside application tag
Download the pdf file in the MyDocs inside Downloads folder
Below is a quick sample of my code (i have commented the other combinations i have tried):
private void checkIfPdfExists(String pdfFileName) {
String uriFile = String.valueOf(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+File.separator+"MyDocs"+File.separator+pdfFileName+".pdf"));
File file = new File(uriFile);
//File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/MyDocs", pdfFileName+".pdf");
//File file = new File(Environment.DIRECTORY_DOWNLOADS+File.separatorChar+"MyDocs"+File.separatorChar+pdfFileName+".pdf");
//File file = new File(Environment.DIRECTORY_DOWNLOADS+File.separatorChar+"MyDocs", pdfFileName+".pdf");
if (file.exists() && file!=null) {
Toast.makeText(getApplicationContext(), file.getPath() + "/n exists", Toast.LENGTH_SHORT).show();
displayFromUri(Uri.parse(file.getPath()));
} else {
beginDownload("https://www.heritagestatic.com/comics/d/history-of-comics.pdf",pdfFileName);
}
}
And this is how i define the path when i download the pdf, the downloader works as it should:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.addRequestHeader("Accept", "application/pdf");
request.setDescription(file_name);
request.setTitle("Getting your doc");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"MyDocs/"+file_name+".pdf");
I did some research before posting the question and in some threads i found that is related to Android Q, but i can't find a real solution for it. Any help would be appreciated, thanks in advance!
The solution to my problem was how i was referring to file path and the method used for download. As #blackapps mentioned that if you use "setDestinationInExternalFilesDir" to save the file, the proper way to check if the file exist is with "getExternalFilesDir", in my case:
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+File.separator+"MyDocs"+File.separator+pdfFileName+".pdf");

How to download file into data/data/com.****.*** folder and open it

I need to download some pdf files into data/data/com.**.* folder.
Those files are application specific and only application should read and display it that's the reason storing on data/data/com.**.* folder.
Please let me know how to download into that folder and open/read it in the application.
I know how to download it into SD card, but I do not have idea to downloading to application specific folder.
Please let me know some code examples to do this and also I need to know the capacity/size of the data/data/com.**.* folder.
As long as you want write your own applications Data folder, you can create a FileOutputStream like this FileOutputStream out = new FileOutputStream("/data/data/com.**.*/somefile"); than use that output stream to save file. Using the same way you can create a FileInputStream and read the file after.
You will get Permission Denied if you try to access another application's data folder.
I am not sure for capacity but you can calculate the size of the data folder using this
File dataFolder = new File("/data/data/com.**.*/");
long size = folderSize(dataFolder);
...
public static long folderSize(File directory) {
long length = 0;
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
else
lengthlong += folderSize(file);
}
return length;
}
Hi here i am attaching the link of a tutorial explained.
http://www.mysamplecode.com/2012/06/android-internal-external-storage.html
and there are many discussions going on internet that you should root your phone in order to access the data from data/data folder and I am also attaching some links about the discussion, I hope these are also some of the links that are related to your question
where do i find app data in android
How to access data/data folder in Android device?
and as well as some links that makes out the things without rooting your phone i mean
You can get access to /data/data/com*.* without rooting the device
http://denniskubes.com/2012/09/25/read-android-data-folder-without-rooting/
To Write file
FileOutputStream out = new FileOutputStream("/data/data/your_package_name/file_name.xyz");
To Read file
FileInputStream fIn = new FileInputStream(new File("/data/data/your_package_name/file_name.xyz"));
Now you have your input stream , you can convert it in your file according to the file type .
I am giving you example if your file is contain String data the we can do something like below ,
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String mDataRow = "";
String mBuffer = "";
while ((mDataRow = myReader.readLine()) != null) {
mBuffer += mDataRow + "\n";
}
Remember to add write file permission to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Copying resource file to external storage on android not working

I'm working on a mediaplayer application and am trying to have some default songs get put on the phone in case the user doesn't have any on their phone (I'm pulling the list of actual songs via mediastore).
So I have the songs put in the res/raw folder and fun the following code to copy them. It seems to be copying ok (since astro file browser and other apps see them fine) but the mediastore still can't find them.
I think it's something with the permissions on the file but I'm not sure what. Anybody know why?
InputStream song = getResources().openRawResource(R.raw.aquarel);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "aquarel.mp3");
Log.e(TAG, "File1: " + file.getPath());
OutputStream copySong = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int readvalue = 0;
readvalue = song.read(buffer);
while (readvalue > 0) {
copySong.write(buffer, 0, readvalue);
readvalue = song.read(buffer);
}
copySong.close();
"When you add files to Android’s filesystem these files are not picked
up by the MedaScanner automatically.
...
If you want your files to be added to the media library, you can do so
either by using the MediaStore content provider, or by using the
MediaScanner."
You can add them by sending a broadcast:
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
(Source)

ANDROID internal storage file delete/exist not working for me

First of all, I want to know if making a file without extension is okay. For example, making a file with ".txt" extendsion will make it a txt file on a computer, but I don't know it matters in android. And I noticed that when working on eclipse, I could deleted a fild with the extensions but couldn't delete a file without a extension.
I want my program to delete a file in the internal storage (com.name.application folder) but it's not working for me.
I make a file with
FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
write with
bos = new BufferedOutpuStream(openFileOutput(FileName,Context.MODE_APPEND)
bos.write(newVocabFile.getBytes());
and I want to delete with
FILE file = new File(fileName);
fild.delete();
I did researches on google and applied different methods to my codes, but every method did not work for me. Because .delete() does not work properly, .exist() does not work either. I tired making the mile with and without extension but both ways did not work either.
I really need to get through this in order to finish my application. Please help me
You have a typo on this line
FILE file = new File(fileName);
fild.delete();
It should be
File file = new File(fileName);
file.delete();

Download file to external public storage without knowing the filename

My HTTP-server allows downloading files with a 'dynamic' url: e.g. http://myserver.com/query?id=12345 which will give me my_song.mp3.
The filename is indicated in the content-disposition header.
Downloading this kind of file with Android DownloadManager works fine but I want to be able to control where the file is being saved to.
The normal way to do this would be to call
DownloadManager.Request r = new DownloadManager.Request(uri);
r.setDestinationInExternalPublicDir(String dirType, String subPath);
Unfortunately this requires to know the filename up front which I don't know. I tried calling the above function with a null for subPath but it does not work...

Categories

Resources