【问题标题】:Rename a file using Java使用 Java 重命名文件
【发布时间】:2010-11-12 15:02:51
【问题描述】:

我们可以将文件如test.txt 重命名为test1.txt 吗?

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

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

【问题讨论】:

  • 您的最后一段根本没有描述重命名操作。它描述了一个追加操作。

标签: java file rename file-rename


【解决方案1】:

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

关于在 Java 中重命名文件,请参阅 documentation 以了解 File 类中的 renameTo() 方法。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 不知道,但这与 Pierre 发布的完全一样,没有源代码...
    【解决方案3】:

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

    【讨论】:

    【解决方案4】:

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

    如果您想将第二个文件的内容附加到第一个文件,请查看FileOutputStream with the append constructor optionThe same thing for FileWriter。您需要读取文件的内容以使用输出流/写入器追加和写出它们。

    【讨论】:

      【解决方案5】:

      通过将文件移动到新名称来重命名文件。 (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();
        }
      

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

          简而言之:

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

          【讨论】:

          • Path 是一个接口,它的唯一实现是 WindowsPath、ZipPath 和 AbstractPath。这对于多平台实现来说会是一个问题吗?
          • 嗨@user2104648,这里(tutorials.jenkov.com/java-nio/path.html)是一个关于如何在Linux环境中处理文件的例子。基本上,您需要使用 java.nio.file.Paths.get(somePath) 而不是使用您提到的实现之一
          • 什么是路径源 = ...?
          • @kr37 完美回答!
          • @KorayTugay。 Path source = file.getAbsolutePath(); 其中file 是需要重命名的文件。
          【解决方案8】:

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

                  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");
                  }
          

          【讨论】:

          • 由于某种原因,如果我运行该文件,它就会消失。
          【解决方案9】:
          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);
          

          【讨论】:

            【解决方案10】:
            Files.move(file.toPath(), fileNew.toPath()); 
            

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

            【讨论】:

              【解决方案11】:

              运行代码在这里。

              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();
                      }
                  }
              }
              

              【讨论】:

              • 通常最好解释一个解决方案,而不是仅仅发布一些匿名代码行。你可以阅读How do I write a good answer,也可以阅读Explaining entirely code-based answers
              • 复制和重命名通常是不同的操作,所以我认为应该清楚地标明这是一个副本。这也恰好是不必要的慢,因为它复制字符而不是字节。
              【解决方案12】:

              试试这个

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

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

              【讨论】:

              • 这与 9 年前 Pierre 给出的公认答案有何不同?
              【解决方案13】:

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

              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");
              

              【讨论】:

                【解决方案14】:

                是的,您可以使用 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));
                           }
                        });
                
                    }
                }
                

                }

                【讨论】:

                  猜你喜欢
                  • 2015-03-12
                  • 1970-01-01
                  • 2017-04-10
                  • 2011-01-02
                  • 2014-01-20
                  • 2016-05-29
                  • 2014-08-03
                  • 2011-10-28
                  相关资源
                  最近更新 更多