How to Write File in Kotlin: Simple File Writing Guide
In Kotlin, you can write text to a file using the
writeText() function on a File object. Simply create a File with the desired path and call writeText("your text") to save content to the file.Syntax
To write text to a file in Kotlin, use the File class from java.io package. The main function is writeText(), which takes a string and writes it to the file.
- File(path): Creates a file object for the given path.
- writeText(text): Writes the provided text to the file, replacing existing content.
kotlin
import java.io.File fun main() { val file = File("filename.txt") file.writeText("Hello, Kotlin!") }
Example
This example creates a file named example.txt and writes a greeting message to it. If the file does not exist, it will be created automatically.
kotlin
import java.io.File fun main() { val file = File("example.txt") file.writeText("Welcome to Kotlin file writing!") println("File written successfully.") }
Output
File written successfully.
Common Pitfalls
Common mistakes when writing files in Kotlin include:
- Not importing
java.io.File. - Using a relative path without knowing the current working directory, which may cause the file to be created in an unexpected location.
- Not handling exceptions that may occur if the file is not writable or the path is invalid.
Always ensure you have write permissions and consider using try-catch to handle errors gracefully.
kotlin
import java.io.File fun main() { try { val file = File("/invalid_path/example.txt") file.writeText("This may fail if path is invalid.") println("File written successfully.") } catch (e: Exception) { println("Error writing file: ${e.message}") } }
Output
Error writing file: /invalid_path/example.txt (No such file or directory)
Quick Reference
- File(path): Create file object.
- writeText(text): Write string to file (overwrites).
- appendText(text): Add string to end of file.
- exists(): Check if file exists.
- readText(): Read file content as string.
Key Takeaways
Use File(path).writeText(text) to write text to a file in Kotlin.
The writeText function overwrites existing file content.
Handle exceptions to avoid crashes when file paths are invalid or inaccessible.
Relative file paths depend on the program's working directory.
Use appendText(text) to add content without overwriting.