How to open and read text files in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.1, “How to open and read a text file in Scala.”

Back to top


You want to open a plain-text file in Scala and process the lines in that file.

Back to top


There are two primary ways to open and read a text file:

Table of Contents

  1. Problem
  2. Solution
Back to top

How to read a file URL in Java and Scala

I thought this might be harder, but if you have a file URL like “file:///Users/al/SherlockHolmes.txt”, and want to read those file contents as a Java URL, the process in Java and Scala is simple, as shown in this Scala code:

How to associate filename extensions with your Mac Java application alvin August 15, 2010 - 12:50am

A little disappointed that I couldn't find some content on my own website, this article is essentially just a pointer to another article, so ...

Vim insert commands

Vim FAQ: What is the Vim insert command?

Short answer: Type the letter 'i' while in Vim command mode. You'll then be able to type text into your document, right where the cursor is currently positioned.

Vim insert commands

Longer answer: There are several other variations of the Vim insert command you can use:

Java file open, read, and write utilities alvin February 1, 2010 - 8:13am

Java file utilities FAQ: Do you have any Java file utilities you can share?

As I was working on another Java/Swing application this weekend, I ran across my "Java file utilities" class, and I thought I'd share that class here today. It's nothing too major, but it does include Java methods that let you open, read, write, and copy files using Java.

A Perl “read file into array” example

Perl read file FAQ: How can I read a file into an array in Perl (Or, Can you share a Perl read file into array example?)

One of the really cool things about Perl is that it's super-easy to read a file into a Perl array. This is really handy any time you need to read a file for any reason.

A Perl read file into array example

If you want to read a file into a Perl array, you actually only need one line of code, like this:

Perl: How to test if a file exists

Perl file exists FAQ: How can I perform a test to see if a file exists with Perl?

You can test to see if a file exists with the Perl "-e" file operator.

A Perl file exists example

Here's a short test/example: