8 minutes read

You can do a lot of interesting things with files: for example, you can read their content or write something new. In this topic you will learn how to write files. There are different ways to write a file in Kotlin. We won't consider all of them here: let's start with the selected basics.

Writing files with writeText()

You may already know that the main class for working with files is java.io.File, and Kotlin library adds some features through the extension functions. An object of File type just provides a reference with the path to a file. First, you need to import this library:

import java.io.File

Suppose we want to create a text file called MyFile with the following text:

"It is awfully hard work doing nothing!"

To do that, we need to use the aforementioned library, create a File(pathName: String) object, and use the writeText(text: String) function which sets the text content of a file:

val myFile = File("MyFile.txt") //file name must be indicated in parentheses 
myFile.writeText("It is awfully hard work doing nothing!")

Mission accomplished: the text is in the file! You can see it in the current project directory where it was saved by default. Notice, if you just create a File object, you will not create a file, it's just an object.

Suppose we didn't write the file in the current directory but elsewhere. In that case, simply indicate the path to it like this:

val myFile = File("D://Users/myFile.txt")
myFile.writeText("It is awfully hard work doing nothing!")

If you run the code, you can see that our file with the specified text was created on the corresponding disk following this path.

If the file has access restrictions or has already been opened in another process, AccessDeniedException is thrown. Also, you can determine the current directory with System.getProperty ("user.dir"):

val workingDirectory = System.getProperty ("user.dir") 

Note that the path separator depends on the platform. For example, for Windows it is '\', and for UNIX and MAC it is '/'. To correctly define the separator, use the File.separator in the library java.io.File. We declare the variable containing the separator of our OS:

// separator
val separator = File.separator 

//combine path to string: 
val absolutePath = "${workingDirectory}${separator}myFile.txt" 

Last but not least, let’s talk about code style: the file name should be put into a separate string variable. You can also put the text into a variable. Take a look:

val fileName = "myFile.txt"
val textToFile = "If we learn to process our code carefully, we’ll grow as programmers."
File(fileName).writeText(textToFile)

This is considered good style, so it would be great if you make it a rule for yourself.

Formatting and processing

Sometimes we need to apply formatting to improve the layout of the text. For example, we may need to move the text to a new line. In this case, the \n comes in handy:

val fileName = "myFile.txt"
File(fileName).writeText("Just \nlook\n at\n that!")

If you need to make an indented paragraph, use \t:

val fileName = "myFile.txt"
File(fileName).writeText("\tThere’s a tab")

Feel free to experiment with this: the use of such tools is very easy yet effective. Even if the string with your text does not look very good, the text in the final file will look fabulous!

Overwriting and appending

You know how to create files with text content, but what if you need to overwrite an existing file? For this, you can use the same feature writeText() for File(), which specifies the path to the document we want to overwrite. Let's rewrite our text and use a different quote:

File(fileName).writeText("Beware of bugs in the above code; I have only proved it correct, not tried it")

You can open the file and make sure it worked!

Logically, if the specified file did not exist on this path, it will be created.

Okay, and what if you wanted to retain the current content of the file and add something else to it? Then we’ll need the appendText(text: String) function:

val fileName = "myFile.txt"
File(fileName).appendText(", Donald E. Knuth said.")

You can see that the text in our file now looks like this:

Beware of bugs in the above code; I have only proved it correct, not tried it, Donald E. Knuth said.

Writing byte arrays

Sometimes you need to write Bytes, not Strings. Let's briefly consider two other options for file writing.

writeBytes(array: ByteArray) – with this function, we can write an array of bytes to this file.

val arrayOfBytes = byteArrayOf(1, 2, 3) // create an array
// another way:
// val arrayOfBytes = mutableListOf<Byte>(1, 2, 3).toByteArray() 

File(fileName).writeBytes(arrayOfBytes)

appendBytes(array: ByteArray) – this function is analogous to the appendText() method, only applied to an array of bytes:

val arrayOfBytes = byteArrayOf(0, 1, 2)
File(fileName).appendBytes(arrayOfBytes)

Note, these functions work with ByteArray. The Array structure is similar to the MutableList, you cannot resize it, but you can modify elements. You can easily convert MutableList to ByteArray and vice versa with toByteArray() and toMutableList() functions.

Using Path

Kotlin also offer Path object to work with files. You can use this object by importing import kotlin.io.path.*. This object offers us various functions to handle directories and files. Including reading and writing.

val textFile = Path("/path/to/textFile.txt") // path to the file
textFile.writeText("This is some text.") // write text to the file
textFile.appendText("This is some text.") // append text to the file

val bytesFile = Path("/path/to/bytesFile.txt") // path to the file
bytesFile.writeBytes(byteArrayOf(1, 2, 3)) // write bytes to the file
bytesFile.appendBytes(byteArrayOf(1, 2, 3)) // append bytes to the file

Conclusion

We've looked at the writeText() function, which is used to write or overwrite a file, and appendText() used for adding something new. For a better view of the text, benefit from escape sequences, and for a better view of the code, take the path to the file into a separate variable.

Now you know how to write and edit files: you are fully armed and ready to go!

282 learners liked this piece of theory. 6 didn't like it. What about you?
Report a typo