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 - 如果掃描器已被關閉。 |