I searched and tried a lot before asking this.
But all the code that I'm trying is not working.
I want the file to be stored in the download
folder and be accessible from the user also if he uninstalls the app.
I also tried using opencsv
library. Could you provide a tested
way to create a csv
or txt
file and store to download
folder?
Asked
Active
Viewed 3,989 times
4

l000000l
- 330
- 1
- 3
- 14
1 Answers
5
Save to to publicDir(Downloads folder) you first need permission.WRITE_EXTERNAL_STORAGE check docs
Note this won't work without permmissions
private void saveData(){
String csv_data = "";/// your csv data as string;
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//if you want to create a sub-dir
root = new File(root, "SubDir");
root.mkdir();
// select the name for your file
root = new File(root , "my_csv.csv");
try {
FileOutputStream fout = new FileOutputStream(root);
fout.write(csv_data.getBytes());
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
boolean bool = false;
try {
// try to create the file
bool = root.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (bool){
// call the method again
saveData()
}else {
throw new IllegalStateException("Failed to create image file");
}
} catch (IOException e) {
e.printStackTrace();
}
}

denniz crypto
- 451
- 4
- 10
-
NICE! I had permissions problem... checking again them solved the issue. Thanks! – l000000l May 22 '20 at 12:20
-
why do we need write permission for android 11 and above? google chrome does it without any permission – Jazib Khan Nov 30 '22 at 08:45