English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn different methods to create strings from a given file set in Kotlin.
Before creating a string from the file, we assume that insrcThere is a folder namedtest.txtfile.
This istest.txtContent
This is a Test file.
import java.nio.charset.Charset import java.nio.file.Files import java.nio.file.Paths fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" val encoding = Charset.defaultCharset(); val lines = Files.readAllLines(Paths.get(path), encoding) println(lines) }
When running the program, the output is:
[This is a, Test file.]
In the above program, we use the System's user.dir property to get the current directory stored in the variable path. SeeKotlin program to get the current directory to getMore information.
We use defaultCharset() to encode the file. If you know the encoding, please use it; otherwise, using the default encoding is safe.
Then, we use the readAllLines() method to read all lines in the file. It gets the file path and encoding, and returns all lines in a list as shown in the output.
Because readAllLines may also throw IOException, we must define the main method
public static void main(String[] args) throws IOException
import java.nio.charset.Charset import java.nio.file.Files import java.nio.file.Paths fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" val encoding = Charset.defaultCharset() val encoded = Files.readAllBytes(Paths.get(path)) val lines = String(encoded, encoding) println(lines) }
When running the program, the output is:
This is a Test file.
In the above program, we did not get a list of strings, but a string lines containing all the content.
For this, we use the readAllBytes() method to read all bytes from the given path. Then we convert these bytes to a string using the default encoding.
The equivalent Java code is as follows:Java Program to Create String from File Content.