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

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

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


当前回答

通过将文件移动到新名称来重命名文件。(FileUtils来自Apache Commons IO lib)

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }

其他回答

我不喜欢java.io.File.renameTo(…),因为有时它不重命名文件,你不知道为什么!它只返回true (false)如果失败,它不会抛出异常。

另一方面,java.nio.file.Files.move(…)更有用,因为它会在失败时抛出异常。

试试这个

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

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

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

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 . renameto()。

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

摘自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*/);