如何在文件已经存在的情况下使用附加递增数字创建新文件? [英] How to create a new file with additional incrementing number when file already exists?

查看:90
本文介绍了如何在文件已经存在的情况下使用附加递增数字创建新文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码

 字符串文件名=test.txt
路径路径=路径获得(文件名);
文件f = null;
if(Files.exists(path)){
LOGGER.warn(File allready exists!);
f =新建文件(COPYOF-+ fileName);
} else {
f = new File(fileName);

code $


它可以工作,但是它不能完成我想要的工作。

我想这样做的适当的方式。



第一次下载文件应该命名为 test.txt 。第二个 - test(1).txt 。第三: test(2).txt 等。



现在将它下载为 test.txt ,第二次命名为 COPYOF-test.txt ,第三次尝试就是重载 COPYOF-test.txt file。



我正在寻找一个合适的方法来实现这个解决方案,但我不知道如何...

解决方案

工作代码:

  String fileName =test.txt; 

字符串扩展=;
String name =;

int idxOfDot = fileName.lastIndexOf('。'); //获取最后一个索引。分开扩展
extension = fileName.substring(idxOfDot + 1);
name = fileName.substring(0,idxOfDot);

Path path = Paths.get(fileName);
int counter = 1;
文件f = null;
while(Files.exists(path)){
fileName = name +(+ counter +)。+ extension;
path = Paths.get(fileName);
counter ++;
}
f = new File(fileName);

解释:

首先分开扩展名文件名,不带扩展名,并设置 counter = 1 然后检查这个文件是否存在。如果存在,则转到步骤2,否则转到步骤3. code> + + 计数器 + + 扩展并检查这个文件是否存在。如果存在,则用增量 counter 重复此步骤。 这里用最新生成的文件名创建文件。


I have a small piece of code

String fileName = "test.txt"
Path path = Paths.get(fileName);
File f = null;
if (Files.exists(path)) {
    LOGGER.warn("File allready exists!");
    f = new File("COPYOF-" + fileName);
} else {
    f = new File(fileName);
}

It works, but it doesn't do what I want it to do...

I would like to do it the "proper" way.

On first download the file should be named test.txt. On second - test(1).txt. On third: test(2).txt etc.

Currently it is downloading it as test.txt and the second time it is named COPYOF-test.txt and on the third attempt it is just overriding the COPYOF-test.txt file.

I'm looking for a proper way to implement this solution but I have no idea how to do it...

解决方案

Working Code:

String fileName = "test.txt";

String extension = "";
String name = "";

int idxOfDot = fileName.lastIndexOf('.');   //Get the last index of . to separate extension
extension = fileName.substring(idxOfDot + 1);
name = fileName.substring(0, idxOfDot);

Path path = Paths.get(fileName);
int counter = 1;
File f = null;
while(Files.exists(path)){
    fileName = name+"("+counter+")."+extension;
    path = Paths.get(fileName);
    counter++;
}
f = new File(fileName);

Explanation:

  1. Firstly separate extension and file name without extension and set counter=1 then check if this file exists or not. If exists go to step 2 otherwise got to step 3.

  2. If file exists then generate new name with file name without extension+(+counter+)+extension and check this file exists or not. If exists then repeat this step with increment counter.

  3. Here create file with latest generated file name.

这篇关于如何在文件已经存在的情况下使用附加递增数字创建新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆