8

I want to rename a file in the system by Scala code. The equivalent of what can be done by bash like,

mv old_file_name new_file_name

I am not asking about renaming a scala source code file, but a file residing in the system.

Goku__
  • 940
  • 1
  • 12
  • 25

3 Answers3

14

Consider

import java.io.File
import util.Try

def mv(oldName: String, newName: String) = 
  Try(new File(oldName).renameTo(new File(newName))).getOrElse(false)

and use it with

mv("oldname", "newname")

Note mv returns true on successful renaming, false otherwise. Note also that Try will catch possible IO exceptions.

elm
  • 20,117
  • 14
  • 67
  • 113
  • 1
    You are totally ignoring the return value of `renameTo`. In other words, whenever `renameTo` just returns `false` (indicating that it could not rename the file) instead of throwing an exception, `mv` will return `true` anyway, as if the operation had succeeded (when it did not). You should replace `.isSuccess` with `getOrElse(false)`. – Régis Jean-Gilles Jun 03 '15 at 16:44
6

See renameTo of java.io.File. In your case this would be

new File("old_file_name").renameTo(new File("new_file_name"))
Roman
  • 5,651
  • 1
  • 30
  • 41
1

Use Guava:

Files.move(new File("<path from>"), new File("<path to>"))
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155