使用 Java 重命名文件 [英] Rename a file using Java

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

问题描述

我们可以将一个文件如 test.txt 重命名为 test1.txt 吗?

Can we rename a file say test.txt to test1.txt ?

如果 test1.txt 存在,它会重命名吗?

If test1.txt exists will it rename ?

如何将其重命名为已经存在的 test1.txt 文件,以便将 test.txt 的新内容添加到其中以备后用?

How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?

推荐答案

复制自 http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html

// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

if (file2.exists())
   throw new java.io.IOException("file exists");

// Rename file (or directory)
boolean success = file.renameTo(file2);

if (!success) {
   // File was not successfully renamed
}

附加到新文件:

java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);

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

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