Scala script to copy files

Viewed 23954

I want to copy file a.txt to newDir/ from within a scala script. In java this would be done by creating 2 file streams for the 2 files, reading into buffer from a.txt and writing it to the FileOutputStream of the new file. Is there a better way to achieve this in scala? May be something in scala.tools.nsc.io._. I searched around but could not find much.

10 Answers

If you don't care too much about speed, you can make your life slightly easier by reading the file using scala.io.Source (this implementation is for 2.7.7):

def copyF(from: java.io.File, to: String) {
  val out = new java.io.BufferedWriter( new java.io.FileWriter(to) );
  io.Source.fromFile(from).getLines.foreach(s => out.write(s,0,s.length));
  out.close()
}

But Source goes to all the trouble of parsing the file line by line, and then you just write it out again without actually processing the lines. Using byte read/write Java style will be considerably faster (about 2-3x last time I benchmarked it).


Edit: 2.8 eats newlines, so you have to add them back in the write.

The os-lib project makes it easy to copy a file in Scala:

os.copy(
  os.pwd/"src"/"test"/"resources"/"a_file.csv",
  os.pwd/"newDir"/"a_file.csv"
)

The library uses java.nio and java.io underneath the hood, but hides all the messiness from end users. It's the easiest modern way to perform filesystem operations, by far. See here for more info.

If you don't wanna use anything external, just do it as you would have done it in Java. The nice thing, is that you can.

Scalax has scalax.io.FileExtras.copyTo(dest : File). But developement seems to have stopped.

Related