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 - 如果扫描器已被关闭。 |