Java Scanner nextLine() 方法
定义和用法
nextLine()
方法返回扫描器中直到下一个换行符之前的所有字符组成的字符串,或者如果没有更多的换行符,则返回直到扫描器末尾的所有字符。
实例
逐行输出文件内容:
import java.io.File; // 导入 File 类 import java.io.FileNotFoundException; // 导入此类以处理错误 import java.util.Scanner; // 导入 Scanner 类以读取文本文件 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("发生错误。"); e.printStackTrace(); // 打印错误堆栈跟踪 } } }
语法
public String nextLine()
技术细节
返回: | 返回扫描器中下一行文本的字符串值。 |
---|---|
抛出: |
|