首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java:如果已经存在同名文件,如何在目录中复制文件

Java:如果已经存在同名文件,如何在目录中复制文件
EN

Stack Overflow用户
提问于 2015-09-13 08:31:13
回答 3查看 3.5K关注 0票数 1

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

如果已经有一个名为xyz.png的文件,并且我试图保存一个具有相同名称的屏幕快照,我希望将其保存为xyz(1).png,而不是替换现有的xyz.png。

下面是我使用的脚本:

代码语言:javascript
运行
复制
  File scrFile = ((TakesScreenshot)cd).getScreenshotAs(OutputType.FILE);

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

回答 3

Stack Overflow用户

发布于 2015-09-13 08:36:02

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

票数 1
EN

Stack Overflow用户

发布于 2015-09-13 08:41:04

你可以这样做:

代码语言:javascript
运行
复制
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));
}
票数 1
EN

Stack Overflow用户

发布于 2015-09-13 08:43:14

这应该会让你走上正确的轨道:

代码语言:javascript
运行
复制
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);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32547806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档