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?