Kotlin Create File

Kotlin Create File – In Kotlin, new file could be created using File.createNewFile(), File.writeText(text :String), Files.writeBytes() etc. There are many other ways to create a file in Kotlin. We shall look into the code implementation for some of them using examples.

Example – Kotlin Create File – File.createNewFile()

File.createNewFile() creates a new file if it does not exist already and returns Boolean value of true. If the file does exist already at the path provided, the method returns false. The file created is empty and has zero bytes written to it.

Using File.createNewFile() is the best and safest procedure to create a new file. Most of the other methods, we go through in this tutorial, would overwrite the file if it exists which may result in the loss of existing data which is not desired in some cases.

In the following example, we try to create a new file with name data.txt. For the first time, the file is created and true is returned. When we try to create the file for second time, as file data.txt is already created, we get false.

Example – File.writeText()

File.writeText() creates a new file if it does not exist already and writes the text (string argument) to the file. If an empty string is provided, the file is created and nothing is written to it. By default the file is encoded as UTF-8. Passing any other charset as second argument encodes the file accordingly.

Note : In case, the file already exists, it is overwritten and the existing data is lost.

Use this method if you are sure that the file does not exist already or overwriting the existing data does not affect your application.

Example – File.writeBytes()

File.writeBytes() creates a new file if it does not exist already and writes the raw bytes of the ByteArray provided to the file created. If an empty ByteArray is provided, the file is created and nothing is written to it.

Note : In case, the file already exists, it is overwritten and the existing data is lost.

Use this method if you are sure that the file does not exist already or overwriting the existing data does not affect your application.

Conclusion

In this Kotlin Tutorial – Kotlin Create File, we have learnt how to create a new file using File.createNewFile(). Also we have seen how File.writeText() and File.writeBytes() could be used to create a file and the side effects of overwriting the existing file if it already exists, with ample Examples.