Java Scanner nextLine() 方法
示例
逐行输出文件内容
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();
}
}
}
自己动手试一试 »
定义和用法
nextLine()
方法返回一个字符串,其中包含扫描器中直到下一个换行符的所有字符,如果没有更多换行符,则返回直到扫描器末尾的所有字符。
语法
public String nextLine()
技术详情
返回 | 一个 String 值,包含扫描器中的下一行文本。 |
---|---|
抛出 |
NoSuchElementException - 如果扫描器中没有更多行。IllegalStateException - 如果扫描器已被关闭。 |