Created
September 2, 2013 10:52
-
-
Save lhohan/6411647 to your computer and use it in GitHub Desktop.
helper "use" method using currying for automatic resource management From http://stackoverflow.com/questions/2225214/scala-script-to-copy-files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
If you really want to do it yourself instead of using a library like commons-io, you can do the following in version 2.8. Create a helper method "use". It will give you a form of automatic resource management. | |
def use[T <: { def close(): Unit }](closable: T)(block: T => Unit) { | |
try { | |
block(closable) | |
} | |
finally { | |
closable.close() | |
} | |
} | |
Then you can define a copy method like this: | |
import java.io._ | |
@throws(classOf[IOException]) | |
def copy(from: String, to: String) { | |
use(new FileInputStream(from)) { in => | |
use(new FileOutputStream(to)) { out => | |
val buffer = new Array[Byte](1024) | |
Iterator.continually(in.read(buffer)) | |
.takeWhile(_ != -1) | |
.foreach { out.write(buffer, 0 , _) } | |
} | |
} | |
} | |
Note that the buffer size (here: 1024) might need some tuning. | |
share|improve this answer | |
answered Jun 12 '10 at 13:40 | |
Ruediger Keller | |
1,309612 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment