This code (written mostly by yourself) and modified by me to save a CSV file works for new files.
try {
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/text/");
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);
fileName = contentsFromFile[0] + "-Test-cert-" + formattedDate + ".csv";
File file = new File(directory, fileName);
OutputStream output = getApplicationContext().getContentResolver().openOutputStream(Uri.fromFile(file));
CSVWriter writer = new CSVWriter(new OutputStreamWriter(output));
writer.writeNext(contentsFromFile);
writer.close();
System.out.println("CFF: " + Arrays.toString(contentsFromFile));
Toast.makeText(getApplicationContext(), "CSV Created", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "CSV Creating Failed", Toast.LENGTH_LONG).show();
}
but when I try to update a file instead of creating a new one using the following code, it fails.
try {
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS + "/text/");
File file = new File(directory, fileName);
OutputStream output = getApplicationContext().getContentResolver().openOutputStream(Uri.fromFile(file));
CSVWriter writer = new CSVWriter(new OutputStreamWriter(output));
writer.writeNext(contentsFromFile);
writer.close();
System.out.println("CFF: " + Arrays.toString(contentsFromFile));
Toast.makeText(getApplicationContext(), "CSV Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "CSV Saving Failed", Toast.LENGTH_LONG).show();
}
The error is:
W/System.err: java.io.FileNotFoundException: open failed: EEXIST (File exists)
How do I persuade it to ignore the existing file and overwrite regardless?
This was never an issue with the pre-Android 10 method but it is now.