How do I rename a file in Scala?

后端 未结 3 1782
一生所求
一生所求 2021-01-12 10:12

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

相关标签:
3条回答
  • 2021-01-12 10:28

    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.

    0 讨论(0)
  • 2021-01-12 10:43

    Use Guava:

    Files.move(new File("<path from>"), new File("<path to>"))
    
    0 讨论(0)
  • 2021-01-12 10:48

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

    new File("old_file_name").renameTo(new File("new_file_name"))
    
    0 讨论(0)
提交回复
热议问题