Java Scanner close() 方法
示例
完成檔案讀取後,使用 close()
方法
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
執行示例 »
定義和用法
close()
方法關閉掃描器正在讀取的檔案或輸入流。呼叫 close()
方法後,當前 Scanner 物件將無法再使用。
注意:關閉透過 System.in
建立的掃描器將關閉 System.in
流本身,使其無法使用。最好只對檔案使用 close()
方法。
語法
public void close()
相關頁面
Java 教程:建立和寫入檔案。