public class AtomicFile

Static library support version of the framework's android.util.AtomicFile, a helper class for performing atomic operations on a file by writing to a new file and renaming it into the place of the original file after the write has successfully completed.

Atomic file guarantees file integrity by ensuring that a file has been completely written and sync'd to disk before renaming it to the original file. Previously this is done by renaming the original file to a backup file beforehand, but this approach couldn't handle the case where the file is created for the first time. This class will also handle the backup file created by the old implementation properly.

Atomic file does not confer any file locking semantics. Do not use this class when the file may be accessed or modified concurrently by multiple threads or processes. The caller is responsible for ensuring appropriate mutual exclusion invariants whenever it accesses the file.


Public constructors

AtomicFile(@NonNull File baseName)

Create a new AtomicFile for a file located at the given File path.

Public methods


Delete the atomic file.


Call when you have failed for some reason at writing to the stream returned by startWrite.


Call when you have successfully finished writing to the stream returned by startWrite.

@NonNull File

Return the path to the base file.

@NonNull FileInputStream

Open the atomic file for reading.


A convenience for openRead that also reads all of the file contents into a byte array which is returned.

@NonNull FileOutputStream

Start a new write operation on the file.

Extension functions

final @RequiresApi(value = 17) byte[]

Gets the entire content of this file as a byte array.

final @RequiresApi(value = 17) @NonNull String
AtomicFileKt.readText(AtomicFile receiver, Charset charset)

Gets the entire content of this file as a String using UTF-8 or specified charset.

final @RequiresApi(value = 17) void
    AtomicFile receiver,
    Function1<FileOutputStreamUnit> block

Perform the write operations inside block on this file.

final @RequiresApi(value = 17) void
AtomicFileKt.writeBytes(AtomicFile receiver, byte[] array)

Sets the content of this file as an array