作爲一個學校練習,我用Java編寫了一個方法來搜索文件中的一個字符。這裏是代碼:此文件對象保持打開狀態嗎?
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,所以我很確定我不必明確地關閉它,但是文件對象呢?
相關的問題http://stackoverflow.com/questions/4752266/why-java-io-file-doesnt-have-a-close-method – 2013-05-06 01:32:45
我想你在這裏的東西。 – noel 2013-05-06 01:33:44
據我可以告訴這是它歸結爲什麼。感謝您的觀點Mukesh。 – noel 2013-05-06 02:05:46