2015-10-20 13 views
1

我有一個小小的一段代碼如何在文件已存在時使用附加增量編號創建新文件?

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); 
} 

它的工作原理,但它不會做我想做的事情......

我想這樣做「正確」的方式。

第一次下載該文件應命名爲test.txt。第二個 - test(1).txt。在第三:test(2).txt

目前,它正在下載它作爲test.txt和第二次它被命名爲COPYOF-test.txt並在第三次嘗試它只是重寫COPYOF-test.txt文件。

我在尋找實施這一解決方案以適當的方式,但我不知道該怎麼辦呢?

+0

你能添加一些代碼,比如你所在的功能稱它。 –

+0

看看在這個線程的答案https://stackoverflow.com/questions/29294470/get-filename-with-date-and-trailing-counter – SubOptimal

回答

3

工作代碼:

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); 

說明:

  1. 首先分離extensionfile name without extension並設置counter=1然後檢查該文件存在。如果存在,則轉到步驟2否則有步驟3

  2. 如果文件存在,然後生成新名稱file name without extension + ( + counter + ) + extension並檢查該文件是否存在。如果存在,則以增量counter重複此步驟。

  3. 這裏用最新生成的文件名創建文件。

+0

工程就像一個魅力!謝謝你,先生! – dziki

1
String fileName = "test.txt"; 
String[] parts = fileName.split("."); 
Path path = Paths.get(fileName); 
File f = null; 
int i = 1; 
while (Files.exists(path)) { 
    LOGGER.warn("File allready exists!"); 
    i++; 
    path = Paths.get(parts[0] + "(" + i + ")" + parts[1]); 
} 
f = new File(parts[0] + "(" + i + ")" + parts[1]); 

PS:I'dd添加特定的方法只是爲了incrementFileName(字符串文件名)。它會更乾淨的代碼。而你,也就能夠檢查特定的情況下(點文件,montextpartie(1)等(3).TXT ...等

+0

是的,你說得對,糾正它 – Fundhor

+0

String [] parts = fileName.split( 「」);將允許一個變量文件名...然後f =新文件(parts [0] +「(」+ i +「)」+ parts [1]); – Margu

+0

@Margu除非文件有多個'.',比如'test.tar.gz';在這種情況下,它會「忘記」文件名/擴展名的一部分。 –

0

要在Fundhor的回答概括:

String fileName = "test.txt"; 
ArrayList<String> fileNameArray = Arrays.asList(fileName.split("\\.")); 
String fileExtension = fileNameArray.remove(fileNameArray.size() - 1); 
StringBuilder strBuilder = new StringBuilder(); 
while (fileNameArray.size() != 0) { 
    strBuilder.append(fileNameArray.remove(0)); 
} 
String fileNameWithoutExtension = strBuilder.toString(); 
Path path = Paths.get(fileName); 
File f = null; 
int i = 1; 
while(Files.exists(path)) { 
    LOGGER.warn("File already exists!"); 
    fileName = fileNameWithoutExtension + "(" + i + ")" + "." + fileExtension; 
    path = Paths.get(fileName); 
} 
f = new File(fileName); 

我的回答也讓文件名與他們的名字時期,例如part1.part2.extension

相關問題