讀取一行文本。一條線被換行符('\ n'),一個回車符('\ r')或一個回車符緊跟着一個換行符被認爲是終止的.------ javadoc 1.8爲什麼BufferedReader.readLine可以讀取沒有行分隔符的行
然後,我有一個文本文件是這樣的:
the first line
the second line
注:的seond行的最後一個字符是「E」是說有不存在回車。
那麼這裏是我的演示代碼。
public void process() throws IOException{
BufferedReader br = new BufferedReader(new FileReader("demo.txt"));
String line;
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
}
實際輸出:
the first line
the second line
那麼我的問題是,爲什麼ReadLine方法可以得到第二線它沒有行分隔符(\ n或\ r或\ n \ r )。
我知道有一個文件結尾(EOF),但它似乎是javadoc不告訴EOF也是明確的行分隔符。
如果我用掃描儀代替BufferedReader中的如下代碼:
public void testScan() throws IOException{
Scanner scan = new Scanner(new FileInputStream("demo.txt"));
String line;
while((line=scan.nextLine())!=null){
System.out.println(line);
}
scan.close();
}
那麼輸出將是:
the first line
the second line
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.demo.Demo.testScan(Demo.java:39)
at com.demo.Demo.main(Demo.java:49)