【问题标题】:Java: How to copy a file in a directory if there exists a file with same name alreadyJava:如果已经存在同名文件,如何复制目录中的文件
【发布时间】:2015-12-09 10:50:18
【问题描述】:

我在 java 中创建了一个自动化脚本,它在每次操作后截取屏幕截图并将其保存在目录中,但是屏幕截图的名称是一个变量(它是我正在测试的链接的名称)。因此,屏幕截图可能已经存在于该目录中。

如果已经有一个名为 xyz.png 的文件,并且我正在尝试保存同名的屏幕截图,我希望将其保存为 xyz(1).png em> 而不是替换现有的 xyz.png

这是我正在使用的脚本:

  File scrFile = ((TakesScreenshot)cd).getScreenshotAs(OutputType.FILE);

  FileUtils.copyFile(scrFile, new File("C:\\saved_screenshots\\"+ScreenshotName+".png"));

【问题讨论】:

    标签: java selenium-webdriver fileutils file-copying


    【解决方案1】:

    使用File.exists() 检查该名称的文件是否已经存在。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      File destinationFile = new File("C:\\saved_screenshots\\"+ScreenshotName+".png");//Create the destination file
      
      //if the destination file already exists, add (1) to the end of the file name. Else copy the scrFile to destinationFile
      if(destinationFile.exists()){
          int count=1;
          while(true){
              File tempFile = new File("C:\\saved_screenshots\\"+ScreenshotName+"("+count+").png");
              if(!tempFile.exists()){
                  break;
              }else{
                  count++;
              }
          }
          FileUtils.copyFile(scrFile, new File("C:\\saved_screenshots\\"+ScreenshotName+"("+count+").png"));
      }else{
          FileUtils.copyFile(scrFile, destinationFile));
      }
      

      【讨论】:

      • 这对于两个以上同名文件会失败,因为您需要(2)(3) 等...
      【解决方案3】:

      这应该会让你走上正轨:

      File scrFile = ((TakesScreenshot) cd).getScreenshotAs(OutputType.FILE);
      String desiredName = "C:\\saved_screenshots\\" + ScreenshotName + ".png";
      File dstFile = new File(desiredName);
      int i = 0;
      while (dstFile.exists ()) {
          i += 1;
          desiredName = "C:\\saved_screenshots\\" + ScreenshotName + " (" + i + ").png";
          dstFile = new File(desiredName);
      }
      FileUtils.copyFile (scrFile, dstFile);
      

      基本上,如果文件存在,则增加一个计数器(更改目标文件名)直到名称可用。

      【讨论】:

      • 感谢大家的回复。我尝试了先检查文件是否存在的方法,它奏效了。然后我意识到为什么不附加一个带有文件名的时间戳。所以使用了内置函数 today=new Date();
      猜你喜欢
      • 2016-06-14
      • 1970-01-01
      • 2023-04-06
      • 2017-04-27
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多