【发布时间】: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