如何在 Scala 中重命名文件? [英] How do I rename a file in Scala?

查看:89
本文介绍了如何在 Scala 中重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 Scala 代码重命名系统中的文件.相当于 bash 可以做的事情,

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

我不是要重命名 scala 源代码文件,而是要重命名驻留在系统中的文件.

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

推荐答案

考虑

import java.io.File
import util.Try

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

并与

mv("oldname", "newname")

注意 mv 在成功重命名时返回 true,否则返回 false.另请注意,Try 将捕获可能的 IO 异常.

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

这篇关于如何在 Scala 中重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆