read file

The Kotlin forEach println syntax

It’s a little hard to move back and forth between Scala and Kotlin because of some of the differences between the languages. Skipping the long story, here’s an example of how to print every line in a list of strings in Kotlin using forEach and println. First the setup:

fun readFile(filename: String): List<String> = File(filename).readLines()
val lines = readFile("/etc/passwd")

Then here are two different ways to use forEach with println:

Scala code to read a text file to an Array (or Seq)

As a quick note, I use code like this read a text file into an Array, List, or Seq using Scala:

def readFile(filename: String): Seq[String] = {
    val bufferedSource = io.Source.fromFile(filename)
    val lines = (for (line <- bufferedSource.getLines()) yield line).toList

Scala file reading performance: Line counting algorithms

Out of curiosity about Scala’s file-reading performance, I decided to write a “line count” program in Scala. One obvious approach was to count the newline characters in the file:

AppleScript code to read file contents into a list (array)

I just ran into a situation where I wanted to use AppleScript to read some file contents into a list/array, and came up with the following code:

set theFile to "/Users/al/Projects/Scala/Sarah/scripts/"
set fileHandle to open for access theFile
set thankYous to paragraphs of (read fileHandle)
close access fileHandle

I can confirm that this code works on my Mac OS X 10.6.8 system. The variable thankYous is a list/array that contains the lines from my file.

Ruby read file example - read a file as a string

Here's a Ruby "read file" example program that shows how to read a file as one string. You just have to pass a file name in to the get_file_as_string method, and this Ruby method will read in all the records from the file, and return the contents of the file as a string.

A Perl extract program

Ever need a program to extract some lines from the middle of a file, say lines 50-500 of a 10,000 line file? Well, I did, so I wrote one in Perl. Here's the code for ", which lets me extract lines from a file by specifying the firstLine and lastLine that I want printed from a file: