-6

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;
}
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • you could check with file.exists method. or something like this `try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW))` – XtremeBaumer Dec 12 '16 at 08:21
  • 3
    If only there was a method on File you could check this with... – wvdz Dec 12 '16 at 08:21
  • 1
    http://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-in-java Its very simple search... – Guy Dec 12 '16 at 08:23

1 Answers1

2

To see if a file name exists simply check it as follow:

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

Note that the file can be also a directory, not necessarelly a true file. If you need also to check if it is a file:

File file = new File(filePath);
if (file.exists() && !file.isDirectory()) { 
    // do something
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56