200

我们可以将文件重命名test.txttest1.txt吗?

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

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

4

14 回答 14

199

复制自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*/);
于 2009-07-21T12:09:22.210 回答
143

简而言之:

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);
于 2013-11-28T07:38:40.047 回答
32

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

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

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

于 2009-07-21T12:08:54.520 回答
30

对于 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 的答案。

于 2013-07-26T16:18:15.333 回答
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();
  }
于 2013-03-17T03:45:52.080 回答
15

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

        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");
        }
于 2015-03-04T16:00:40.637 回答
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"));

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

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
于 2017-03-24T11:27:49.240 回答
5

尝试这个

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

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

于 2018-03-25T18:05:16.710 回答
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));
           }
        });

    }
}

}

于 2018-12-26T21:21:03.137 回答
3

如果只是重命名文件,则可以使用File.renameTo()

如果您想将第二个文件的内容附加到第一个文件,请查看带有附加构造函数选项的 FileOutputStreamFileWriter 的相同内容。您需要读取文件的内容以使用输出流/写入器追加和写出它们。

于 2009-07-21T12:10:49.587 回答
2

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

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

于 2009-07-21T12:08:22.477 回答
1

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

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");
于 2018-09-11T02:49:50.600 回答
1
Files.move(file.toPath(), fileNew.toPath()); 

有效,但仅当您关闭(或自动关闭)所有使用的资源(InputStreamFileOutputStream)我认为与 file.renameToor相同的情况FileUtils.moveFile

于 2017-03-30T13:12:21.340 回答
-2

运行代码在这里。

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("\n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
于 2017-09-23T06:04:58.090 回答