【问题标题】:Is there an operation to move and overwrite files?是否有移动和覆盖文件的操作?
【发布时间】:2013-01-18 13:32:35
【问题描述】:

我正在寻找移动和覆盖文件的操作。我知道Java7 中有一个新方法,但我希望能绕过 Java7。我也知道FileUtils 和Guava 中的方法,但FileUtils 不会覆盖,Guava 也不会记录它。

我也知道,我可以编写自己的方法,我开始了,但是在这里和那里看到了一些问题,所以我希望已经完成了一些事情。

你有什么建议吗?

【问题讨论】:

  • 你真的用过番石榴吗?
  • @nhahtdh 不,我没有尝试过番石榴。但是我声明要实现 Unix mv,并且 mv 不会在没有提示的情况下覆盖。 unixhelp.ed.ac.uk/CGI/man-cgi?mv

标签: java io


【解决方案1】:

纯 Java nio 解决方案可以通过预删除目标实现,如图所示

public void move(File sourceFile, String targetFileName) {
    Path sourcePath = sourceFile.toPath();
    Path targetPath = Paths.get(targetFileName);
    File file = targetFile.toFile();
    if(file.isFile()){
        Files.delete(targetPath);
    }
    Files.move(sourcePath, targetPath);
}

【讨论】:

    【解决方案2】:

    GuavaFiles.write:

    用字节数组的内容覆盖文件

    Files.write(bytes, new File(path));
    

    Files.copy:

    警告:如果 to 表示现有文件,则该文件将 被from的内容覆盖。如果往返参考 同一个文件,该文件的内容将被删除。

    Files.move 使用 copy under the hood。所以假设它也被覆盖是安全的。

    【讨论】:

      【解决方案3】:

      对我有用的最短解决方案:

      File destFile = new File(destDir, file.getName());
      if(destFile.exists()) {
          destFile.delete();
      }
      FileUtils.moveFileToDirectory(file, destDir, true);
      

      【讨论】:

      • 和上面作者说的一样。在移动文件之前他不能删除:(
      【解决方案4】:

      我使用以下方法:

      public static void rename(String oldFileName, String newFileName) {
          new File(newFileName).delete();
          File oldFile = new File(oldFileName);
          oldFile.renameTo(new File(newFileName));
      }
      

      【讨论】:

      • 谢谢,这是我的第一次实现,但我的文件很大。因此,如果在您删除第一个文件后程序会中断,那么您的所有数据都会丢失或传播到某个地方。编辑:这个问题出现了,这就是我问的原因。所以我需要解决这个问题。
      • 我意识到这是一个旧帖子,但我目前正在使用这种方法,它并没有按照作者的要求覆盖,这也是我替换它的原因
      【解决方案5】:

      用于 FileUtils.copyFileToDirectory 的 Apache FileUtils JavaDoc 说:“如果目标文件存在,则此方法将覆盖它。”复制后,您可以在删除前进行验证。

      public boolean moveFile(File origfile, File destfile)
      {
          boolean fileMoved = false;
          try{
          FileUtils.copyFileToDirectory(origfile,new File(destfile.getParent()),true);
          File newfile = new File(destfile.getParent() + File.separator + origfile.getName());
          if(newfile.exists() && FileUtils.contentEqualsIgnoreCaseEOL(origfile,newfile,"UTF-8"))
          {
              origfile.delete();
              fileMoved = true;
          }
          else
          {
              System.out.println("File fail to move successfully!");
          }
          }catch(Exception e){System.out.println(e);}
          return fileMoved;
      }
      

      【讨论】:

        【解决方案6】:

        我已经完成了自己的方法的编写,对于所有对可能的解决方案感兴趣的人,我使用了 ApacheCommons FileUtils,这可能并不完美,但对我来说已经足够好了:

        /**
         * Will move the source File to the destination File.
         * The Method will backup the dest File, copy source to
         * dest, and then will delete the source and the backup.
         * 
         * @param source
         *            File to be moved
         * @param dest
         *            File to be overwritten (does not matter if
         *            non existent)
         * @throws IOException
         */
        public static void moveAndOverwrite(File source, File dest) throws IOException {
            // Backup the src
            File backup = CSVUtils.getNonExistingTempFile(dest);
            FileUtils.copyFile(dest, backup);
            FileUtils.copyFile(source, dest);
            if (!source.delete()) {
                throw new IOException("Failed to delete " + source.getName());
            }
            if (!backup.delete()) {
                throw new IOException("Failed to delete " + backup.getName());
            }
        }
        
        /**
         * Recursive Method to generate a FileName in the same
         * Folder as the {@code inputFile}, that is not existing
         * and ends with {@code _temp}.
         * 
         * @param inputFile
         *            The FileBase to generate a Tempfile
         * @return A non existing File
         */
        public static File getNonExistingTempFile(File inputFile) {
            File tempFile = new File(inputFile.getParentFile(), inputFile.getName() + "_temp");
            if (tempFile.exists()) {
                return CSVUtils.getNonExistingTempFile(tempFile);
            } else {
                return tempFile;
            }
        }
        

        【讨论】:

        • 什么是CSVUtils?
        • 该类的名称。这些是静态方法。
        【解决方案7】:

        如果您将继续编写自己的实用程序,您可能需要查看 Ant 中 copy 任务的 implementation,因为它支持覆盖。

        【讨论】:

        • 感谢您的链接,但我希望有一个现有的解决方案。
        【解决方案8】:

        使用 Apache Commons FileUtils:

          try {         
                FileUtils.moveFile(source, dest);
                print("------------------------------");
                print(name
                        + " moved to "
                        + PropertiesUtil
                                .getProperty(PropertiesUtil.COMPLETED_PATH));
        
            } catch (FileExistsException fe){
        
                if(dest.delete()){
                    try {
                        FileUtils.moveFile(source, dest);
                    } catch (IOException e) {
                        logger.error(e);
                    }
                    print("------------------------------");
                    print(name
                            + " moved to "
                            + PropertiesUtil
                                    .getProperty(PropertiesUtil.COMPLETED_PATH));
                }
            } catch (Exception e) {
        
                logger.error(e);
            }
        

        【讨论】:

          【解决方案9】:

          您还可以使用 https://xadisk.java.net/ 之类的工具来启用对现有文件系统的事务性访问。

          还有一个来自 apache 的替代方案:

          https://commons.apache.org/proper/commons-transaction/apidocs/org/apache/commons/transaction/file/FileResourceManager.html

          【讨论】:

            猜你喜欢
            • 2011-11-17
            • 2012-02-05
            • 2014-09-07
            • 1970-01-01
            • 1970-01-01
            • 2023-04-09
            • 1970-01-01
            • 2011-08-19
            • 2012-08-03
            相关资源
            最近更新 更多