该文件对象是否保持打开状态? [英] Is this file object left open?
本文介绍了该文件对象是否保持打开状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为学校的一项练习,我用Java编写了一种在文件中搜索字符的方法.这是代码:
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);
}
}
这可以满足我的需求,但是我有一个问题. 文件对象是否曾经打开过? 我是否在Scanner对象上使用了try-with-resources,所以我很确定不必显式关闭它,但是文件对象呢? >
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?
推荐答案
文件对象只是路径名的抽象表示,与打开文件无关.因此它无法关闭.
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.
这篇关于该文件对象是否保持打开状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文