Before Kotlin
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String content = sb.toString();
} finally {
br.close();
}
This is a code sample reading a files content in plain old Java. What a mess 🙂
With Kotlin
Look at this beauty!
val file = File("./data.txt")
val contents = file.readText()
val lines = contents.lines()
lines.forEach { println(it) }
Yes there is Apache commons IO and yes since java 7 things have been easier as well, but with Kotlin I feel like I can concentrate on solving problems and not trying to don’t do things wrong 🙂
Further Reading
https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java