【问题标题】:How to Check if the File Name is already exists or not? [duplicate]如何检查文件名是否已经存在? [复制]
【发布时间】:2017-04-27 01:44:41
【问题描述】:

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

为此,我使用以下代码

以下代码的问题是不能保证 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;
}

【问题讨论】:

  • 您可以使用 file.exists 方法进行检查。或类似try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW))
  • 如果文件上有一个方法,您可以使用...进行检查。
  • stackoverflow.com/questions/1816673/… 非常简单的搜索...

标签: java


【解决方案1】:

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

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

请注意,文件也可以是目录,不一定是真正的文件。 如果还需要检查是否为文件:

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

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2015-06-17
    相关资源
    最近更新 更多