10

Using Android's EncryptedFile (androidx.security:security-crypto:1.1.0-alpha01), I can successfully write a file using the following code

File file = new File(context.getFilesDir() + File.separator + filename);
KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
EncryptedFile encryptedFile = null;
try {
    String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
    encryptedFile = new EncryptedFile.Builder(
            file,
            context,
            masterKeyAlias,
            EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build();
} catch (Exception exception) {
    // log error
}

// write file
try {
    BufferedWriter bufferedWriter = new BufferedWriter(
            new OutputStreamWriter(encryptedFile.openFileOutput()));
    bufferedWriter.write(string);
    bufferedWriter.close();
} catch (Exception exception) {
    // log error
}

However, when attempting to overwrite the same file, the write operation fails and the following is thrown

java.io.IOException: output file already exists, please use a new file

I found this to be an explicit check in EncryptedFile's openFileOutput()

if (mFile.exists()) {
    throw new IOException("output file already exists, please use a new file: "
            + mFile.getName());
}

To fix this, I was able to successfully overwrite by deleting the file if it existed before using it to build the EncryptedFile

File file = new File(context.getFilesDir() + File.separator + filename);
if (file.exists()) { file.delete(); }

... remaining code from top snippet above

This seems like a hack, but I also don't understand the choice to throw an exception for mFile.exists() in openFileOutput(). Is there a correct/better way to overwrite an EncryptedFile?

2
  • 2
    Deleting the file first seems fine to me.
    – Henry
    Jul 28, 2020 at 6:25
  • 2
    I've had some cases where the if (file.exists()) { file.delete(); } does not work, and this exception: throw new IOException("output file already exists, please use a new file: " + mFile.getName()); is still thrown. Any ideas? Apr 8, 2021 at 7:30

1 Answer 1

-1

The error message you're encountering, "java.io.IOException: output file already exists, please use a new file," indicates that your Java program is trying to create or write to a file, but that file already exists. To resolve this issue, you can take one of the following approaches:

  1. Use a New File Name: Change the name of the output file so that it doesn't conflict with an existing file. This is the simplest solution if you don't need to overwrite the existing file.

  2. Check for Existing File: Before creating or writing to the file, you can check if it already exists using Java's File class. If it exists, you can choose to either delete it, rename it, or take any other necessary action based on your program's requirements.

    import java.io.File;
    
    File outputFile = new File("output.txt");
    
    if (outputFile.exists()) {
        // You can choose to delete, rename, or handle the existing file as needed
        outputFile.delete(); // Delete the existing file
        // Alternatively, rename it: outputFile.renameTo(new File("new_output.txt"));
    }
    
    // Now, you can create/write to the file without conflict
    // ...
    
  3. Append to Existing File: If you want to add data to an existing file without overwriting it, you can open the file in append mode. This will allow you to add content to the end of the file.

    import java.io.FileWriter;
    import java.io.IOException;
    
    try {
        FileWriter writer = new FileWriter("output.txt", true); // The 'true' parameter is for append mode
        // Write data to the file
        writer.write("New data to append");
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

Choose the approach that best fits your requirements and the behavior you want for your program.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.