我正在尝试编写一个函数,该函数将采用项目名称的字符串表示形式,并尝试创建具有匹配名称的文件夹。如果这样的文件夹已经存在,我想创建一个名称相同的文件夹,然后是" -1",或者如果" -1"版本已经存在,它将创建一个" -2"而不是版本。
例如,如果项目名称是CandyMachine,那么该文件夹将被称为CandyMachine。如果已存在该名称的文件夹,则会尝试创建名为CandyMachine-1的文件夹。如果CandyMachine-1已经存在,那么它将尝试创建名为CandyMachine-2等的文件夹。
以下是我到目前为止实施的代码:
private static String getOutputPath(String projName){
String newPath = "Projects" + File.separator + projName;
File pathFile = new File(newPath);
if(pathFile.exists()){
int i = 1;
while(pathFile.exists()){
pathFile = new File(newPath + "-" + i);
i++;
}
newPath += "-" + Integer.toString(i);
newPath += File.separator + "src";
return newPath;
}
else
return newPath;
}
关于上述代码的问题是,如果我可以通过在while循环中重复创建新的File对象来潜在地导致内存泄漏吗?如果是这样的话,我该如何避免呢?据我所知,我无法更改已存在的File对象的路径。有没有更好的方法来检查我要检查的内容?
答案 0 :(得分:0)
关于上述代码的问题是,如果我可能通过在while循环中重复创建新的File对象而导致内存泄漏吗?
没有。只要引用超出范围,就有资格进行垃圾回收。因此,您创建的所有File
对象最终都将被垃圾回收。
现在,还有一个问题在2014年更为根本:不再使用File
,请使用Path
。以下是使用更新的,更好的文件API编写代码的方法:
private static final Path PROJECT_DIR = Paths.get("Projects");
// ...
private static String getOutputPath(final String projName)
{
Path ret = PROJECT_DIR.resolve(projName);
int index = 1;
while (Files.exists(ret))
ret = PROJECT_DIR.resolve(projName + '-' + index++);
return ret.toString();
}
当然,这个代码可以大大改进;例如,只检查路径是否存在,而不是路径实际上是目录,常规文件还是符号链接(是的,新API可以检测到; File
不能)。
答案 1 :(得分:-1)
等一下,当输入参数只有一个String
代表Project Name
时,为什么需要while loop
不是while loop
迭代所有文件只是为了查找是否采用了令牌,如何将其分解为两步,其中在第一步中,您有一个FileNameFilter
列出所有以文件开头的文件Project Name
然后处理文件名以创建适当的目录。
File dir = new File("Projects" + File.separator + projName);
String[] foundFiles = dir.listFiles(new FilenameFilter() {
boolean accept(File dir, String name) {
return name.startsWith(projName);
}
});
for (String filename : foundFiles) {
// Process filename by finding the maximum token after project name and creating the directory based on the last found token +1
}