How to Check if the File Name is already exists or not? : <p>Before Storing a file i am checking if the file name already exists (to prevent overriding)</p>

<p>For this i am using the following code</p>

<p>The issue with the below code is that there is no guarantee that newimage does not already exist. </p>

<pre><code>        public static String ImageOverrideChecker(String image_name)throws IOException{
        String newimage = "";
        ArrayList&lt;String&gt; image_nameslist = new ArrayList&lt;String&gt;();
                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;
}
</code></pre>
