scala Scala脚本复制文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2225214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:56:05  来源:igfitidea点击:

Scala script to copy files

scalafilecopy

提问by kulkarni

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.

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

回答by Alain O'Dea

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

出于性能原因,最好使用java.nio.Channel进行复制。

Listing of copy.scala:

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.txtwith the following content:

要尝试此操作,请创建一个名为test.txt的文件,其中包含以下内容:

Hello World

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

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

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

Verify that test-copy.txthas Hello Worldas its content.

验证测试copy.txt具有Hello World作为其内容。

回答by Brian Agnew

Why not use Apache Commons IOand FileUtils.copyFile()in particular ? Note that FileUtils has a large number of methods to copy files/directories etc.

为什么不特别使用Apache Commons IOFileUtils.copyFile()?请注意,FileUtils 有大量方法来复制文件/目录等。

回答by Martin

Java 7 is now out and you have another option: java.nio.file.Files.copy. The probably easiest solution (And with Scalas superior importeven easier). Provided that fromand toare strings as in your question:

Java 7 现已发布,您还有另一个选择:java.nio.file.Files.copy. 可能是最简单的解决方案(并且使用 Scalasimport更容易)。前提是fromto是您问题中的字符串:

import java.nio.file.StandardCopyOption.REPLACE_EXISTING
import java.nio.file.Files.copy
import java.nio.file.Paths.get

implicit def toPath (filename: String) = get(filename)

copy (from, to, REPLACE_EXISTING)

Of course you should start using java.nio.file.Pathsinstead of strings.

当然你应该开始使用java.nio.file.Paths而不是字符串。

回答by Ruediger Keller

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.

如果你真的想自己做而不是使用像commons-io这样的库,你可以在2.8版本中执行以下操作。创建一个辅助方法“使用”。它将为您提供一种自动资源管理形式。

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.

请注意,缓冲区大小(此处:1024)可能需要进行一些调整。

回答by pawel.panasewicz

Hire sbt.IO. It's pure scala, it can copy only changed files, has usefull routines like copyDirectory, delete, listFilesetc . You can use it as follow:

雇用sbt.IO。这是纯粹的Scala中,它只能复制已更改的文件,具有有用的程序一样copyDirectorydeletelistFiles等。您可以按如下方式使用它:

import sbt._
IO.copyFile(file1, file2)

Note you should add proper dependency:

请注意,您应该添加适当的依赖项:

libraryDependencies += "org.scala-sbt" % "io" % "0.13.0"

libraryDependencies += "org.scala-sbt" % "io" % "0.13.0"

EDIT: Actually this is not a good approach since dependency "org.scala-sbt" % "io" % "version"was compiled using particular scala version and for now you cannot use it with 2.10.X scala version. But maybe in future you will can add double %% in you dependency like "org.scala-sbt" %% "io" % "version"and it will work...

编辑:实际上这不是一个好方法,因为依赖项"org.scala-sbt" % "io" % "version"是使用特定的 scala 版本编译的,现在您不能将它与 2.10.X scala 版本一起使用。但也许将来你可以在你的依赖中添加双 %%"org.scala-sbt" %% "io" % "version"并且它会起作用......

回答by Rex Kerr

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):

如果你不太关心速度,你可以通过使用 scala.io.Source 读取文件让你的生活稍微轻松一些(这个实现是针对 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).

但是 Source 麻烦地逐行解析文件,然后您只需再次写出它,而无需实际处理这些行。使用字节读/写 Java 风格会快得多(上次我对它进行基准测试时大约是 2-3 倍)。



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

编辑:2.8 吃换行符,因此您必须将它们添加回写入中。

回答by Geo

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.

如果你不想使用任何外部的东西,就像你在 Java 中所做的那样。好处是,你可以。

回答by Thomas Jung

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

Scalax有 scalax.io.FileExtras.copyTo(dest : File)。但发展似乎已经停止。

回答by santiajo

From scala-io documentation:

来自scala-io 文档

import scalax.io._
import Resource._

fromFile("a.txt") copyDataTo fromFile("newDir/a.txt")