As an exercise for school I wrote a method in Java that searches for a character in a file. Here is the code:
public static void countLetter(char needle, String hayStack) throws IOException {
File f = new File(hayStack);
try (Scanner in = new Scanner(f)) {
String str = null;
while (in.hasNext()){
str += in.next();
}
char[] charArr = str.toCharArray();
int counter = 0;
for (char c: charArr) {
if (c == needle){
counter++;
}
}
System.out.println(counter);
}
}
This does what I need it to but I have a question. Is the file object ever opened? And if it is, does it ever closed? I used try-with-resources on the Scanner object so I'm pretty sure I don't have to explicitly close that, but what about the file object?
The
File
object can not be opened (and therefore can not be closed) as it is a representation of a file path and not a representation of a file.The
Scanner
class opens your file in order to read it. Your program doesn't callin.close()
so when your method returns theScanner
will not be garbage collected as it still has a reference to an open file. You may also be locking the file depending on how the file was opened by theScanner
.In order for a class to qualify for automatically closing resources in a try-resource block the class must implement
java.lang.AutoCloseable
(orjava.io.Closeable
).Scanner
does not implement these interfaces and so it won't have itsclose()
method called when you exit the try-resource block.Alter the code to:
As the variable is local to your function so it will go out of scope once the function exists, and eventually garbage collection. Answer to your question is NO, in your case file object is not ever opened.
File object is just an abstract representation of a pathname, it has nothing to do with opening a file. So it can not be closed.