Scala: How to read input from one file while writing output to another file

Without much introduction or discussion, here’s a Scala example that shows how to read from one text file while simultaneously writing the uppercase version of the text to a second output file:

import{BufferedWriter, File, FileWriter}
import utils.IOUtils.using

object SemiStreaming extends App {

    val inFile  = "/Users/al/tmp/in.dat"
    val outFile = "/Users/al/tmp/out.dat"

    // caution: this throws a FileNotFoundException if inFile doesn't exist
    using(io.Source.fromFile(inFile)) { inputFile =>
        using(new BufferedWriter(new FileWriter(new File(outFile), true))) { outputFile =>
            for (line <- inputFile.getLines) {
                outputFile.write(line.toUpperCase + "\n")


This example uses the using construct, which I’ve discussed in other Scala file-reading tutorials on this website.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.