首页 > 解决方案 > 如果存在则重命名文件而不是覆盖它

问题描述

当我执行下面的代码时,它会覆盖现有文件。我也想保留旧文件和新文件。在这里可以做什么?我们可以像 Windows 模式一样将它重命名为 Test(1).xlsx、Test(2).xlsx、Test(3).xlsx 吗?

File excel = new File("C:\\TEST\\Test.xlsx");
try (FileInputStream fis = new FileInputStream(excel); 
     XSSFWorkbook book = new XSSFWorkbook(fis);) {
    ..
    ..
    ..
    try (FileOutputStream outputStream = new FileOutputStream("C:\\TEST\\Output\\Test.xlsx")) {
        book.write(outputStream);
    }
}
    

标签: java

解决方案


exists()您可以在开始写入之前使用该方法检查文件是否已存在。如果该文件已存在,则写入另一个文件。

File excel = new File(determineFileName());
try (FileInputStream fis = new FileInputStream(excel);
     XSSFWorkbook book = new XSSFWorkbook(fis);) {
...
}

private String determineFileName(){
  String path = "C:\\TEST\\Test.xlsx";
  int counter = 0;
  while(new File(path).exists()){
    counter++;
    path = "C:\\TEST\\Test(" + counter + ").xlsx";
  }
  return path;
}

推荐阅读