Before Storing a file i am checking if the file name already exists (to prevent overriding)
For this i am using the following code
The issue with the below code is that there is no guarantee that newimage does not already exist.
        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;
}
 
    