I am using a StringBuilder to create a File object, but am also using it to see if the directory the file is located inside of exists:
StringBuilder sbFile = new StringBuilder();
sbFile.append("/home/logs/");
File oFile = new File(sbFile.toString());
if(!oFile.exists())
oFile.mkdir();
sbFile.append("MyLogFile.log");
oFile = new File(sbFile.toString());
But I am worried that reusing the same oFile reference on two different “versions” of the string builder (/home/logs/ vs /home/logs/MyLogFile.log) will create a memory leak. If so, how should I write this differently?
There is no memory leak. The instance of
Filecreated for the first time, will be garbage-collected by JVM when it is no longer used.The other thing is that you don’t really need to use
StringBuilder.Fileclass has a constructor that takes a parent and a filename. Your example could look like this:Also, you may be interested in how garbage collection works in Java.