Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala script to copy files

Tags:

file

copy

scala

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.

like image 399
kulkarni Avatar asked Feb 08 '10 22:02

kulkarni


1 Answers

For performance reasons it is better to use java.nio.Channel to do the copying.

Listing of copy.scala:

import java.io.{File,FileInputStream,FileOutputStream} val src = new File(args(0)) val dest = new File(args(1)) new FileOutputStream(dest) getChannel() transferFrom(     new FileInputStream(src) getChannel, 0, Long.MaxValue ) 

To try this out create a file called test.txt with the following content:

Hello World 

After creating test.txt, run the following from the command line:

scala copy.scala test.txt test-copy.txt 

Verify that test-copy.txt has Hello World as its content.

like image 108
Alain O'Dea Avatar answered Sep 17 '22 00:09

Alain O'Dea