Scala脚本复制文件 [英] Scala script to copy files

查看:145
本文介绍了Scala脚本复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在scala脚本中将文件a.txt复制到newDir /。
在java中,这将通过为2个文件创建2个文件流,从a.txt读入缓冲区并将其写入新文件的FileOutputStream来完成。
有没有更好的方法来实现这个在scala?可能是scala.tools.nsc.io.的东西。

解决方案

出于性能考虑,最好使用java.nio.Channel

pre> 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)
test.txt 的文件:



<$> p $ p> Hello World

创建 test.txt ,从命令行运行以下命令:

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

验证 test-copy.txt Hello World 作为其内容。


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.

解决方案

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.

这篇关于Scala脚本复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆