使用Java重命名文件

218

我们能否将一个名为test.txt的文件重命名为test1.txt

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

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


10
您最后一段并没有描述重命名操作,而是描述了添加操作。 - user207421
15个回答

211

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

33
这段代码在所有情况和平台下都无法正常工作。rename to 方法不可靠:https://dev59.com/bnNA5IYBdhLWcg3wWsUA - Stephane Grenier
2
只有使用 Path 方法对我有效,renameTo 总是返回 false。请查看 kr37 的答案 或者 这个答案 - andras
2
这看起来更像是复制而不是重命名。我错过了什么? - JohnK

157

简而言之:

Files.move(source, source.resolveSibling("newname"));

更多细节:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
以下内容直接从http://docs.oracle.com/javase/7/docs/api/index.html复制而来: 假设我们想将文件重命名为“newname”,并保持文件在相同的目录中:
Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

或者,假设我们想要将一个文件移动到一个新目录,保持相同的文件名,并替换目录中任何现有的同名文件:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);

3
Path是一个接口,其唯一的实现是WindowsPath、ZipPath和AbstractPath。对于跨平台实现,这会成为一个问题吗? - Caelum
1
嗨@user2104648,这里(http://tutorials.jenkov.com/java-nio/path.html)有一个关于如何在Linux环境中处理文件的示例。基本上,您需要使用java.nio.file.Paths.get(somePath)而不是使用您提到的实现之一。 - maxivis
3
"Path source = ..." 是什么意思?(翻译) - Koray Tugay
@kr37 完美的答案! - Gaurav
@KorayTugay。Path source = file.getAbsolutePath(); 这里的 file 是需要重命名的文件。 - yurin
关于Files.move支持的选项以及它能提供哪些跨平台保证的限制(例如在同一文件系统中重命名时原子替换现有目标文件),请参考以下内容。如何在Java中原子地重命名文件,即使目标文件已经存在? - Peter Cordes

32

对于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+,您应该查看并赞同kr37的答案。


32

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

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

如果您想将一个文件的内容附加到另一个文件中,则有许多可用的 writer。根据扩展名,它听起来是纯文本,因此我会看一下 FileWriter


10
不清楚,但这与Pierre发布的完全相同,只是没有源代码... - Thomas Owens

19

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

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

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

17

这是一个简单的重命名文件的方法:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

由于某些原因,如果我运行它,文件就会消失。 - Dmytro Moskovchenko

6
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;

Path yourFile = Paths.get("path_to_your_file\text.txt");

Files.move(yourFile, yourFile.resolveSibling("text1.txt"));

要替换名为"text1.txt"的现有文件:

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);

5

试一下

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

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


1
这与9年前Pierre给出的被接受答案有何不同? - Forage

5

是的,你可以使用 File.renameTo() 方法。但是在将文件重命名为新文件时,请记得要有正确的路径。

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}


3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接