I'm not too experienced, especially when it comes ...
# getting-started
j
I'm not too experienced, especially when it comes to string processing in Kotlin. So sorry if this is a stupid Noob question. Here is the behavior I get and what I'm not really understanding: I have a simple text with six words in three lines separated by commas:
Copy code
Boo,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.
Copy code
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, 2025
p
What if change line separator from "\n" to "\r\n"? Where chars.split is called.
👍 1
j
Thanks. That works. But why?
p
In your file line separator is \r\n. It is Windows default line separator. When you split by \n only, \r is remain in resulting lines.
👍 1
j
Dang Windows Notation! Thanks a lot!
r
You can use
System.lineSeparator()
which will return
\r\n
on Windows and
\n
on *nix systems like macOs and Linux. You can also just use this:
Copy code
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.
Under the hood
File.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 (
\n
), a carriage return (
\r
), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).
👍 1
j
Thanks. Very helpful.