2016-12-12 145 views
-6

之前存儲文件我檢查,如果該文件名已經存在(防止壓倒一切)如何檢查文件名是否已經存在?

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

與下面的代碼的問題是,有沒有保證,newimage尚不存在。

 public static String ImageOverrideChecker(String image_name)throws IOException{ 
     String newimage = ""; 
     ArrayList<String> image_nameslist = new ArrayList<String>(); 
       File file = new File("/Images/"); 
     File[] files = file.listFiles(); 
     for(File f: files){ 
       image_nameslist.add(f.getName()); 
     } 
     if(image_nameslist.contains(image_name)) 
     { 
       Random randomGenerator = new Random(); 
       int randomInt = randomGenerator.nextInt(1000); 
       Matcher matcher = Pattern.compile("(.*)\\.(.*?)").matcher(image_name); 
       if (matcher.matches()) 
       { 
         newimage = String.format("%s_%d.%s", matcher.group(1), randomInt,matcher.group(2)); 
       } 
     } 
     else 
     { 
       newimage = image_name; 
     } 
     return newimage; 
} 
+0

你可以用file.exists方法檢查。或類似這樣的'嘗試(OutputStream出= Files.newOutputStream(路徑,StandardOpenOption.CREATE_NEW))' – XtremeBaumer

+3

如果只有在文件上的方法,你可以檢查... – wvdz

+1

http://stackoverflow.com/questions/ 1816673/how-do-i-check-if-a-file-exists-in-java其非常簡單的搜索... – Guy

回答

2

要查看某個文件名存在簡單的檢查如下:

File file = new File(filePath); 
if (file.exists()) { 
    // do something 
} 

注意的是,文件可以是也目錄,而不是necessarelly真正的文件。 如果你還需要檢查它是否是一個文件:

File file = new File(filePath); 
if (file.exists() && !file.isDirectory()) { 
    // do something 
} 
相關問題