Supported on Android, iOS, macOS, JVM and Kotlin/Native Linux targets
PlatformFile class offers multiple methods to write data to files, from simple strings to binary data and streaming operations.
Writing from ByteArray
The most common way to write data to a file is using thewrite() infix function with a ByteArray:
Writing from String
You can also write a string to a file using thewriteString() function:
Using Sink
For more advanced use cases or when working with large files, you can use thesink() method:
Some provider-backed files (for example, certain Android
content:// URIs) may not expose a reliable size ahead of time. Prefer destination.write(sourceFile) or sourceFile.copyTo(destination) for robust streaming copy behavior.Appending to Files
To append data to an existing file instead of overwriting it, use theappend parameter:
Copying Files
You can easily copy the contents of one file to another using thewrite infix function with another PlatformFile or the copyTo function:
Moving Files
You can move a file from one location to another using theatomicMove function:
Deleting Files
FileKit also provides a method to delete files:recursively defaults to false, so deleting a non-empty
directory fails unless you enable it. Symbolic links (including dangling links)
and Windows directory junctions are removed as links; their targets are left
untouched. Android document URIs continue to use the document provider’s deletion
behavior.
Creating Directories
Before writing to a file, you may need to ensure its parent directory exists:Error Handling
When writing files, you should handle potential errors:Downloading files from web
Supported on JS and WASM targets
Example: Creating a Simple Logger
See also: Reading Files for information on how to read files after writing them.