[英]How to move files from one folder to another in Scala
我是 Scala 的新手。
我用谷歌搜索了很多,但只找到了如何在 Java 中移動文件。 我嘗試使用 Java 移動文件:
import Java.io.File
和兩者: Files.move("FileA", "FileB",StandardCopyOption.REPLACE_EXISTING);
和Files.move("DirA", "DirB",StandardCopyOption.ATOMIC_MOVE);
如何在 Scala 中將文件從一個文件夾移動到另一個文件夾?
您可以使用 Scala 中的 Java API 將文件從一個位置移動到另一個位置。 下面是執行相同操作的代碼,
import java.io.File
import java.nio.file.{Files, StandardCopyOption}
val source = new File("path-to-source-directory").toPath
val destination = new File("path-to-destination-directory").toPath
Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE)
這是java.nio
文檔頁面推薦它的方式。
import java.nio.file.{FileSystems, Files}
val path = FileSystems.getDefault.getPath("/tmp/data.txt")
val newHome = FileSystems.getDefault.getPath("./Downloads")
Files.move(path, newHome.resolve(path.getFileName()))
//res0: java.nio.file.Path = ./Downloads/data.txt
如果您必須進行大量文件處理,我推薦https://github.com/pathikrit/better-files 。
這將像
import better.files._
File("/path/one/file").moveToDirectory(File("path/two"))
一個簡單的方法是使用 scala 中的系統進程構建。 就像使用 bash 一樣。
如果要將“1/1.txt”移動到“2”
$ tree
.
├── 1
│ └── 1.txt
└── 2
在 scala REPL 中:
scala> import scala.sys.process._
import scala.sys.process._
scala> "tree".!!.mkString
res0: String =
".
├── 1
│ └── 1.txt
└── 2
2 directories, 1 file
"
scala> "mv 1/1.txt 2".!!
res1: String = ""
scala> "tree".!!.mkString
res2: String =
".
├── 1
└── 2
└── 1.txt
2 directories, 1 file
將文件移動到另一個目錄有點不同。
scala> "tree".!!.mkString
res3: String =
".
├── 1
└── 2
├── 1.txt
└── 2.txt
2 directories, 2 files
"
scala> Seq("/bin/sh", "-c", "mv 2/* 1").!!
res6: String = ""
scala> "tree".!!.mkString
res7: String =
".
├── 1
│ ├── 1.txt
│ └── 2.txt
└── 2
2 directories, 2 files
"
另見此處: https://alvinalexander.com/scala/how-to-handle-wildcard-characters-running-external-commands
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.