1

I am saving a file in Android Q or higher using the source below.

But if there is a file

Saved as filename (1), filename (2), filename (3)...

I am wondering how to overwrite the file

try {
            ContentValues values = new ContentValues();

            values.put(MediaStore.MediaColumns.DISPLAY_NAME, "menuCategory");       //file name                     
            values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");        //file extension, will automatically add to file
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + "/Kamen Rider Decade/");     //end "/" is not mandatory

            Uri uri = getContentResolver().insert(MediaStore.Files.getContentUri("external"), values);      //important!

            OutputStream outputStream = getContentResolver().openOutputStream(uri);

            outputStream.write("This is menu category data.".getBytes());

            outputStream.close();

            Toast.makeText(view.getContext(), "File created successfully", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(view.getContext(), "Fail to create file", Toast.LENGTH_SHORT).show();
        }
swiftbegineer
  • 329
  • 1
  • 9
  • You should again use the uri you got when you called .insert() to write the file. If you dont know the uri any more then query the media store for filename and relative path to obtain the uri for that file name. – blackapps May 01 '21 at 14:27
  • Glad to see that you're quoting my solution. You should look at the full solutions here: https://stackoverflow.com/a/62879112/3466808, which includes how to find and overwrite files. – Sam Chen May 01 '21 at 19:53

0 Answers0