我们能把test。txt重命名为test1.txt吗?

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

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


当前回答

对于Java 1.6及以下版本,我相信最安全、最干净的API是Guava的Files.move。

例子:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

第一行确保新文件的位置是相同的目录,即旧文件的父目录。

编辑: 我是在开始使用Java 7之前写的这篇文章,Java 7引入了非常类似的方法。所以如果你正在使用Java 7+,你应该看到并投票kr37的答案。

其他回答

您希望在File对象上使用renameTo方法。

首先,创建一个File对象来表示目的地。检查该文件是否存在。如果它不存在,为要移动的文件创建一个新的File对象。在要移动的文件上调用renameTo方法,并检查renameTo的返回值,以查看调用是否成功。

如果要将一个文件的内容附加到另一个文件,有许多可用的写入器。基于扩展,它听起来像是纯文本,所以我会看看FileWriter。

这是我的代码重命名多个文件在一个文件夹成功:

public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
    if(newName == null || newName.equals("")) {
        System.out.println("New name cannot be null or empty");
        return;
    }
    if(extension == null || extension.equals("")) {
        System.out.println("Extension cannot be null or empty");
        return;
    }

    File dir = new File(folderPath);

    int i = 1;
    if (dir.isDirectory()) { // make sure it's a directory
        for (final File f : dir.listFiles()) {
            try {
                File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);

                if(f.renameTo(newfile)){
                    System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                } else {
                    System.out.println("Rename failed");
                }
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

并运行它作为一个例子:

renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");

试试这个

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult

注意: 我们应该总是检查renameTo返回值,以确保重命名文件成功,因为它依赖于平台(不同的操作系统,不同的文件系统),如果重命名失败,它不会抛出IO异常。

如果只是重命名文件,可以使用file . renameto()。

如果您希望将第二个文件的内容附加到第一个文件,请使用附加构造函数选项查看FileOutputStream或FileWriter。您需要读取文件的内容来追加,并使用输出流/写入器将它们写出来。

Files.move(file.toPath(), fileNew.toPath()); 

工作,但只有当你关闭(或自动关闭)所有使用的资源(InputStream, FileOutputStream等),我认为文件的情况相同。renameTo或FileUtils.moveFile。