How to move/rename files in Scala

If you ever need to move a file in Scala, I can confirm that this approach works:

import java.nio.file.{Files, Paths, StandardCopyOption}

val path = Files.move(
    Paths.get(sourceFilename),
    Paths.get(destinationFilename),
    StandardCopyOption.REPLACE_EXISTING
)

if (path != null) {
    println(s"moved the file $sourceFilename successfully")
} else {
    println(s"could NOT move the file $sourceFilename")
}

In that example both sourceFilename and destinationFilename are strings that contain the full, canonical name of the files. For example, the source might be something like /Users/al/Pictures/photo1.jpg and the destination file might be /Users/al/tmp/photo1.jpg. As that example implies, you can move files between different directories with this approach.

There is at least one other way to move a file in Scala, but I found this to be the most direct approach.

A Scala method to move/rename a file

If you want to make that code into a Scala method/function to move a file, here’s a little starter for you:

def moveRenameFile(source: String, destination: String): Unit = {
    val path = Files.move(
        Paths.get(source),
        Paths.get(destination),
        StandardCopyOption.REPLACE_EXISTING
    )
    // could return `path`
}

Pretty much all you have to do is decide what to do about the path variable, i.e., whether you want to return it, and/or how to return it.

More details

The Java Files Javadoc has a lot more detail on the move method, but here are some of the most important notes:

  • Move or rename a file to a target file.
  • By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect.
  • If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved.
  • Moving a file will copy the last-modified-time to the target file if supported by both source and target file stores. Copying of file timestamps may result in precision loss.
  • An implementation may also attempt to copy other file attributes but is not required to fail if the file attributes cannot be copied.

There is much more documentation about the move method, including how it works when trying to move directories, and exceptions that can be thrown, so see that Javadoc page for more information.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.