I am new to Scala.
I\'ve Googled a lot on how to move files in Scala, but have only found how to move files in Java. I tried to move files using Java import Java.io
From my understanding of your question,
you are trying to pass String
variables instead of java.nio.Path
variables to the Files.move()
.
The below way works:
import java.io.File
import java.nio.file.{Files, Path, StandardCopyOption}
val d1 = new File("/abcd").toPath
val d2 = new File("/efgh").toPath
Files.move(d1, d2, StandardCopyOption.ATOMIC_MOVE)
However I see one more issue in your code.
Both StandardCopyOption.REPLACE_EXISTING
and StandardCopyOption.ATOMIC_MOVE
should work but, you can't move a parent directory directly into it's child directory.
$ mv public/ public/images
mv: cannot move ‘public/’ to a subdirectory of itself, ‘public/images’
Instead you might want to move public
-> tmp
-> public/images
os-lib makes it easy to copy files from one directory to another:
os.list(os.pwd/"public").map(os.move.into(_, os.pwd/"pub2"))
The java.io and java.nio libraries are generally difficult to work with (although not that ugly for this particular operation). It's best to rely on os-lib for filesystem operations.
os.move.into
takes two arguments: the file that's being moved and the destination directory.
This code is flexible and easily modifiable. You could easily update it to only move files with a certain file extension.
See here for more info on how to use os-lib.
Refer the below Scala code from my Github : https://github.com/saghircse/SelfStudyNote/blob/master/Scala/MoveRenameFiles.scala
You need to specify your source and target folder in main function:
val src_path = "<SOURCE FOLDER>" // Give your source directory
val tgt_path = "<TARGET FOLDER>" // Give your target directory
It also rename files. If you do not want to rename files, then update as below:
val FileList=getListOfFiles(src_path)
FileList.foreach{f =>
val src_file = f.toString()
//val tgt_file = tgt_path + "/" + getFileNameWithTS(f.getName) // If you want to rename files in target
val tgt_file = tgt_path + "/" + f.getName // If you do not want to rename files in target
copyRenameFile(src_file,tgt_file)
//moveRenameFile(src_file,tgt_file) - Try this if you want to delete source file
println("File Copied : " + tgt_file)
}