0

I have a temporary file created like this :

File myfile = File.createTempFile(fileName + " - ", suffix, activity.getExternalCacheDir());
FileWriter fw = new FileWriter(file); 
CSVWriter writer = new CSVWriter(fw, ' '/* DEFAULT_SEPARATOR */, NO_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
writer.writeNext(entries);
writer.close();

Now, I want to save it to disk at the URL /storage/emulated/0/Android/data/com.example.myproject/files/myfile.csv

So I need to change the URL of myfile and save it to disk with code like this:

FileOutputStream fileOutput = new FileOutputStream(myfile);
// How to change URL of myfile ?
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutput);
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();

How can I do that ? (= how to change URL and save to disk ?)

Thanks !

toto_tata
  • 14,526
  • 27
  • 108
  • 198
  • `new FileOutputStream(file)` That should be `new FileOutputStream(myFile)`. But... you should not have created that file already as new FileOutputSTream() will create the file. But it should not bother either. – blackapps Sep 27 '21 at 10:16
  • I edited my question that was not detailed and accurate enough. – toto_tata Sep 27 '21 at 10:20
  • What you ask makes no sense. `Now, I want to save it to disk at the URL`. The code above that with FileWriter() did already save the csv in that file. – blackapps Sep 27 '21 at 10:39
  • You are right... I get confused because I had another bug (very specific to my app) that disturbed me. Thanks. – toto_tata Sep 28 '21 at 08:32

1 Answers1

0

In order to save files to directories like Android/data you should deal with external storage.

for api 28 and lower use this method :

Android saving file to external storage

Read/Write String from/to a File in Android

and for newer android devices like android 11 (api 29 and later) you should use scoped storage framework check this :

https://developer.android.com/training/data-storage/use-cases

https://medium.com/microsoft-mobile-engineering/scoped-storage-in-android-10-android-11-28d58d989f3c

Otherwise you can save files to Internal Application folder or cache folder without permissions:

https://stackoverflow.com/a/52127190/16728174

Creating temporary files in Android

Do not forget to get proper Read/Write permission for these actions.

user16728174
  • 182
  • 1
  • 4