2016-11-24 91 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)); 

但是,你确定你的操作系统接受/推荐这样的文件名吗?

相关问题