Java Scanner hasNextLine() 方法
示例
逐行輸出檔案內容
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();
}
}
}
執行示例 »
定義和用法
hasNextLine()
方法如果掃描器中還有下一行文字可用,則返回 true。一行文字是一個或多個字元序列,其後跟著換行符或掃描器內容的末尾。
語法
public boolean hasNextLine()
技術詳情
返回 | 一個 boolean 值,如果還有下一行文字可用,則為 true。 |
---|---|
丟擲 | IllegalStateException - 如果掃描器已被關閉。 |