Jobby
10/26/2025, 8:41 AMBoo,Boo,Boo,Boo,Boo,Boo
Foo,Foo,Foo,Foo,Foo,Foo
Goo,Goo,Goo,Goo,Goo,Goo
This is my code together with the output I get as comments.
import java.io.File
fun main() {
val chars: String = File(
"C:\\Work\\Kotlin\\test\\src\\main\\resources\\MyTest.txt"
).readText(Charsets.UTF_8)
val lines = chars.split("\n")
println("Number of Lines: ${lines.size}") // Number of Lines: 3
println(lines[0]) // Boo,Boo,Boo,Boo,Boo,Boo
println(lines[1]) // Foo,Foo,Foo,Foo,Foo,Foo
println(lines[2]) // Goo,Goo,Goo,Goo,Goo,Goo
val myList1 = lines[0].split(",")
val myList2 = lines[1].split(",")
val myList3 = lines[2].split(",")
println("myList1: $myList1") // ]
println("Number of Words: ${myList1.size}") // Number of Words: 6
println("myList2: $myList2") // ]
println("Number of Words: ${myList2.size}") // Number of Words: 6
println("myList3: $myList3") // myList3: [Goo, Goo, Goo, Goo, Goo, Goo]
println("Number of Words: ${myList3.size}") // Number of Words: 6
}
As you can see it only outputs myList3 correctly. myList1 and myList2 just output ']'. But if you look at the size, it seems like it processed my string correctly.
And the thing is, this depends on which line is the last in the txt file. It just outputs the last line the way I'd expect, but not the previous ones.
Why is that?
Is this a bug?
JDK: corretto-23.0.2
Ide: IntelliJ IDEA 2025.1.5.1 (Community Edition) - Build #IC-251.28293.39, built on September 2, 2025PHondogo
10/26/2025, 9:05 AMJobby
10/26/2025, 9:18 AMPHondogo
10/26/2025, 9:20 AMJobby
10/26/2025, 9:31 AMRob Elliot
10/26/2025, 10:34 AMSystem.lineSeparator() which will return \r\n on Windows and \n on *nix systems like macOs and Linux.
You can also just use this:
val lines = File(
"C:\\Work\\Kotlin\\test\\src\\main\\resources\\MyTest.txt"
).readLines()
and leave it to the stdlib to work out what line endings the file has.Rob Elliot
10/26/2025, 10:37 AMFile.readLines() ends up using <http://java.io|java.io>.BufferedReader.readLine(), whose doc states:
A line is considered to be terminated by any one of a line feed (), a carriage return (\n), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).\r
Jobby
10/26/2025, 2:02 PM