Java 如何检查文件名是否已经存在?

Java 如何检查文件名是否已经存在?,java,Java,在存储文件之前,我检查文件名是否已经存在(以防止覆盖) 为此,我使用以下代码 下面代码的问题是不能保证newimage不存在 public static String ImageOverrideChecker(String image_name)throws IOException{ String newimage = ""; ArrayList<String> image_nameslist = new ArrayList<St

在存储文件之前,我检查文件名是否已经存在(以防止覆盖)

为此,我使用以下代码

下面代码的问题是不能保证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;
}
公共静态字符串ImageOverrideChecker(字符串图像\u名称)引发IOException{
字符串newimage=“”;
ArrayList image_nameslist=新建ArrayList();
File File=新文件(“/Images/”);
File[]files=File.listFiles();
用于(文件f:文件){
image_nameslist.add(f.getName());
}
if(image_nameslist.contains(image_name))
{
Random randomGenerator=新的Random();
int randomInt=randomGenerator.nextInt(1000);
Matcher Matcher=Pattern.compile((.*)\.(.*)).Matcher(图像名称);
if(matcher.matches())
{  
newimage=String.format(“%s_u%d.%s”,matcher.group(1),randomInt,matcher.group(2));
}
}
其他的
{
newimage=图像名称;
}
返回新图像;
}

要查看文件名是否存在,只需按如下方式检查:

File file = new File(filePath);
if (file.exists()) { 
    // do something
}
请注意,该文件也可以是目录,而不一定是真正的文件。 如果您还需要检查它是否为文件:

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

您可以使用file.exists方法进行检查。或者类似这样的东西
try(OutputStream out=Files.newOutputStream(path,StandardOpenOption.CREATE_NEW))
如果文件上有一个方法,您可以用它检查一下。。。这是非常简单的搜索。。。