Writing files
Write files with FileKit Core in Kotlin Multiplatform
FileKit Core provides a consistent API for writing files across all platforms. The 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 the write()
infix function with a ByteArray
:
Writing from String
You can also write a string to a file using the writeString()
function:
Using Sink
For more advanced use cases or when working with large files, you can use the sink()
method:
Appending to Files
To append data to an existing file instead of overwriting it, use the append
parameter:
Copying Files
You can easily copy the contents of one file to another using the write
infix function with another PlatformFile
or the copyTo
function:
Moving Files
You can move a file from one location to another using the atomicMove
function:
Deleting Files
FileKit also provides a method to delete files:
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
FileKit provides a convenient way to download files in web environments (JS and WASM targets). This functionality allows users to save files from your web application to their local device:
Example: Creating a Simple Logger
See also: Reading Files for information on how to read files after writing them.