File Reading in Java and Scala

Written on October 1st, 2009 by Thorone shout

Today we are going to look at reading files in Java and how to do the same thing in Scala.

This is normally how we read files in Java.First we open a reading stream, then read the content and process it,and at last we close the stream.

package com.justthor;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SampleFileReader {

  /**
   * @param args
   */
  public static void main(String[] args) {
    BufferedReader in; 
    try {
      // Open file
      in = new BufferedReader(new FileReader("test.txt"));
          String str;
       
          // Start reading
          while ((str = in.readLine()) != null) {
        // Print the content
        System.out.println(str);
          }
          
          // Close the stream
          in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
  }
}

With some third party libraries, such as Apache Common Io, we can simplify the code to something like this.

package com.justthor;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class SampleFileReader {

  /**
   * @param args
   */
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    try {
      List<String> contents = FileUtils.readLines(new File("test.txt"));
      for ( String content : contents ) {
        System.out.println(content);
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Well, it does look a bit simple now compare to the previous version. But we only manage to type 1 or 2 lines less than the previous version. This is due to we are force to handle the checked IOException. What if we try to achieve the same thing using Scala?

package com.justthor

import scala.io.Source

object SampleFileReader {
 def main(args : Array[String]) = {
  Source fromFile("test.txt") getLines foreach { println }
 }
}

Its much simple, right? Scala provides an util for IO named Source. This util read the file and get the contents by calling getLines method. This getLines method returns a Iterator[String]. And from there we can process the content by looping the returned iterator. We can use Source util to do more than reading files. I will provide more examples in the next few posts.

Happy coding. :)

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Live
  • Reddit
Filed under Programming Tags:,

One Comments to “File Reading in Java and Scala”

Leave a Reply

(required)

(required)