java - 如果存在则重命名文件而不是覆盖它
问题描述
当我执行下面的代码时,它会覆盖现有文件。我也想保留旧文件和新文件。在这里可以做什么?我们可以像 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);
}
}
解决方案
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;
}
推荐阅读
- python - 如何在 for 循环(日期时间)中步进一周(7 天)
- c# - 在 C# 上添加整数列表
- javascript - NUXT:使用 async fetch 作为 mixin,如何访问要覆盖的页面数据
- visual-studio-code - VSCode问题匹配器正则表达式与我的错误输出不匹配
- python - pandas 聚合数据,同时保持一列不变
- asp.net-mvc-4 - 控制器类和方法上的 ASP.NET MVC 4 自定义授权过滤器
- vba - Excel 宏不会从可执行文件运行
- ios - 如何在命令中为以该字符串命名的标签使用字符串变量值?
- visual-studio-2015 - 无法在 Visual Studio 2015 中使用引用
- sql - SQL查找互惠关系