2016-11-24 90 views
0

之前存儲文件我檢查,如果該文件名已經存在(防止壓倒一切)如何添加特殊字符的文件名在這種情況下

爲此,我現在用的是下面的代碼

import java.io.File; 
import java.util.ArrayList; 
import java.util.Random; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 


public class Test { 
    public static void main(String[] args) { 
     String imagename = checkImage("big_buck_bunny.mp4"); 
     System.out.println(imagename); 
    } 

    public static String checkImage(String image_name) { 
     String newimage = ""; 
     ArrayList<String> image_nameslist = new ArrayList<String>(); 
     File file = new File("C:\\Users\\Public\\Videos\\Sample Videos\\"); 
     File[] files = file.listFiles(); 
     for (File f : files) { 
      image_nameslist.add(f.getName()); 
     } 
     long l = System.currentTimeMillis(); 
     if (image_nameslist.contains(image_name)) { 
      Random randomGenerator = new Random(); 
      int randomInt = randomGenerator.nextInt(100); 
      Matcher matcher = Pattern.compile("(.*)\\.(.*?)").matcher(image_name); 
      if (matcher.matches()) { // <== test input filename is OK? 
       newimage = String.format("%s_%d.%s", matcher.group(1),randomInt, matcher.group(2)); 
      } 
     } 
     else { 
      newimage = image_name; 
     } 
     return newimage; 
    } 
} 

和輸出我得到的是

big_buck_bunny_50.mp4 

代替randomInt在上面的代碼,是有可能增加一些特殊的字符@前後使輸出看起來像\

[email protected]@.mp4 
+0

你試過了嗎?如果操作系統接受它,應該不成問題。 – ata

+1

我認爲你最好不要檢查那樣的文件名。如果不同的文件名引用同一個文件,例如不區分大小寫的文件系統,它將會失敗。使用'exists()'方法更好地創建'File'對象abd檢查。在你的代碼中也不能保證'newimage'不存在。 – Axel

回答

1

就形成使用隨機整數特殊字符的字符串,然後將其包含在調用String.format()。我對您的電話做的唯一更改是用%s替換%d,並使用隨機字符串代替隨機整數。

String randStr = "@" + String.valueOf(randomInt) + "@"; 
newimage = String.format("%s_%s.%s", matcher.group(1), randStr, matcher.group(2)); 

但是,你確定你的操作系統接受/推薦這樣的文件名嗎?

相關問題