Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move file/files from one folder to another in Scala

Tags:

java

scala

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.File, using both:

Files.move("FileA", "FileB", StandardCopyOption.REPLACE_EXISTING);
Files.move("DirA", "DirB", StandardCopyOption.ATOMIC_MOVE); 

but it didn't work. My code looks like this:

Files.move("/public", "/public/images", StandardCopyOption.ATOMIC_MOVE);

I want to move files from public to public/images.

like image 517
Sangam Thapa Avatar asked Oct 25 '25 15:10

Sangam Thapa


2 Answers

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

like image 93
Gayatri Mahesh Avatar answered Oct 27 '25 05:10

Gayatri Mahesh


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)
}
like image 33
Saghir Hussain Avatar answered Oct 27 '25 04:10

Saghir Hussain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!