java - memory with multiple uses of "new File" -
i trying write function take string representation of project name , effort create folder matching name. if such folder exists, want create folder same name followed "-1", or if "-1" version exists, create "-2" version instead.
for example, if project name candymachine folder called candymachine. if folder name exists, effort create folder named candymachine-1. if candymachine-1 exists, effort create folder named candymachine-2, etc.
here code have implemented far:
private static string getoutputpath(string projname){ string newpath = "projects" + file.separator + projname; file pathfile = new file(newpath); if(pathfile.exists()){ int = 1; while(pathfile.exists()){ pathfile = new file(newpath + "-" + i); i++; } newpath += "-" + integer.tostring(i); newpath += file.separator + "src"; homecoming newpath; } else homecoming newpath; }
my question regarding above code if can potentially cause memory leak repeatedly creating new file objects within while loop? if case, how can avoid it? far know unable alter path of already-existing file object. there improve way check trying check?
my question regarding above code if can potentially cause memory leak repeatedly creating new file objects within while loop?
no. long reference falls out of scope, eligible garbage collection. therefore, file
objects create garbage collected.
now, there problem more fundamental in 2014: don't utilize file
anymore, utilize path
. here how write code using newer, , far better, file 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++); homecoming ret.tostring(); }
of course, code vastly improved; instance, existence of path checked, not whether path directory, regular file or symlink (yes, new api can observe that; file
cannot).
java memory-management new-operator
No comments:
Post a Comment