Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rename a file in Scala?

Tags:

scala

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.

like image 255
Goku__ Avatar asked Jun 03 '15 08:06

Goku__


2 Answers

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.

like image 65
elm Avatar answered Oct 20 '22 18:10

elm


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

new File("old_file_name").renameTo(new File("new_file_name"))
like image 26
Roman Avatar answered Oct 20 '22 19:10

Roman