使用Java重命名文件

163 java rename file file-rename

我们可以重命名文件说test.txttest1.txt

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

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

Pie*_*rre 168

复制自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
}
Run Code Online (Sandbox Code Playgroud)

要附加到新文件:

java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);
Run Code Online (Sandbox Code Playgroud)

  • 此代码不适用于所有情况或平台.重命名方法不可靠:http://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows (20认同)
  • 只有“Path”方式对我有用,“renameTo”总是返回 false。检查[kr37的答案](/sf/answers/1418221031/)或[这个答案](/sf/answers/967826681/) (2认同)
  • 这看起来更像是复制而不是重命名。我缺少什么? (2认同)

kr3*_*r37 94

简而言之:

Files.move(source, source.resolveSibling("newname"));
Run Code Online (Sandbox Code Playgroud)

更多详情:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Run Code Online (Sandbox Code Playgroud)

以下内容直接从http://docs.oracle.com/javase/7/docs/api/index.html复制:

假设我们要将文件重命名为"newname",将文件保存在同一目录中:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));
Run Code Online (Sandbox Code Playgroud)

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

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

  • Path 是一个接口,其唯一实现是 WindowsPath、ZipPath 和 AbstractPath。这对于多平台实施来说会是一个问题吗? (3认同)
  • 什么是路径源 = ... ? (3认同)

Tho*_*ens 29

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

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

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

  • 不知道,但这与Pierre发布的完全相同,没有源代码...... (8认同)

Zol*_*tán 24

对于Java 1.6及更低版本,我认为最安全,最干净的API是Guava的Files.move.

例:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());
Run Code Online (Sandbox Code Playgroud)

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

编辑: 我在开始使用Java 7之前编写了这个,它引入了一种非常类似的方法.因此,如果你使用Java 7+,你应该看到并支持kr37的答案.


Bra*_*don 18

通过将文件移动到新名称来重命名文件.(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();
  }
Run Code Online (Sandbox Code Playgroud)


sen*_*ior 13

这是重命名文件的简便方法:

        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");
        }
Run Code Online (Sandbox Code Playgroud)


Kir*_* Ch 5

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"));
Run Code Online (Sandbox Code Playgroud)

用名称“text1.txt”替换现有文件:

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)


ano*_*knr 5

尝试这个

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
Run Code Online (Sandbox Code Playgroud)

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

  • 这与 Pierre 9 年前给出的公认答案有何不同? (2认同)

小智 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));
           }
        });

    }
}
Run Code Online (Sandbox Code Playgroud)

}


Yuv*_*val 2

据我所知,重命名文件不会将其内容附加到具有目标名称的现有文件的内容中。

关于在 Java 中重命名文件,请参阅class 中方法的文档renameTo()File