The Artima Developer Community
Sponsored Link

Scala Buzz
Improving java.io.File with Scala

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Zemian Deng

Posts: 49
Nickname: zdeng
Registered: Jan, 2008

Zemian Deng is the creator of SweetScala web framework
Improving java.io.File with Scala Posted: Nov 22, 2008 4:31 PM
Reply to this message Reply

This post originated from an RSS feed registered with Scala Buzz by Zemian Deng.
Original Post: Improving java.io.File with Scala
Feed Title: thebugslayer
Feed URL: http://www.jroller.com/thebugslayer/feed/entries/atom?cat=%2FScala+Programming
Feed Description: Notes on Scala and Sweet web framework
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Zemian Deng
Latest Posts From thebugslayer

Advertisement
Don't you wish java.io.File class would provide you these methods?
  • File#deleteAll // remove directory recursively
  • File#write(line) // write a single line into a new file
  • File#foreachLine{ line => /* process line */ } // loop through each line in file with your processing codes
With scala, this can be done with an implicit converter to a extra helper class that provide these methods.
import java.io._
class FileHelper(file : File) {
  def write(text : String) : Unit = {
    val fw = new FileWriter(file)
    try{ fw.write(text) }
    finally{ fw.close }
  }
  def foreachLine(proc : String=>Unit) : Unit = {
    val br = new BufferedReader(new FileReader(file))
    try{ while(br.ready) proc(br.readLine) }
    finally{ br.close }
  }
  def deleteAll : Unit = {
    def deleteFile(dfile : File) : Unit = {
      if(dfile.isDirectory){
        val subfiles = dfile.listFiles
        if(subfiles != null)
          subfiles.foreach{ f => deleteFile(f) }
      }
      dfile.delete
    }
    deleteFile(file)
  }
}
object FileHelper{
  implicit def file2helper(file : File) = new FileHelper(file)
}

//Now you can test it.
import FileHelper._
val dir = new File("/tmp/mydir/nested_dir")
dir.mkdirs
val file = new File(dir, "myfile.txt")
file.write("one\ntwo\nthree")
file.foreachLine{ line => println(">> " + line) }
dir.deleteAll

Hope these are helpful to other.

Read: Improving java.io.File with Scala

Topic: Binary Reading and Writing Combinators for Java Previous Topic   Next Topic Topic: The Downward Spiral: from Scala to Haskell to Clojure

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use