BufferedReader的readLine()方法是阻塞式的, 若是到達流末尾, 就返回null, 但若是client的socket末經關閉就銷燬, 則會產生IO異常. 正常的方法就是使用socket.close()關閉不須要的socket.java
從一個有若干行的文件中依次讀取各行,處理後輸出,若是用如下方法,則會出現除第一行外行首字符丟失現象socket
String str = null;
br=new BufferedReader(new FileReader(fileName));
do{
str = buf.readLine());
}while(br.read()!=-1);
如下用法會使每行都少首字符
while(br.read() != -1){
str = br.readLine();
}
緣由就在於br.read() != -1 這判斷條件上。 由於在執行這個條件的時候其實它已經讀取了一個字符了,然而在這裏並無對讀取出來的這個字符作處理,因此會出現少一個字符,若是你這裏寫的是while(br.readLine()!=null)會出現隔一行少一行!
建議使用如下方法
String str = null;
while((str = br.readLine()) != null){
//System.out.println(str);//此時str就保存了一行字符串
}函數
這樣應該就能夠無字符丟失地獲得一行了oop
雖然寫IO方面的程序很少,但BufferedReader/BufferedInputStream卻是用過好幾回的,緣由是:學習
此次是在藍牙開發時,使用兩個藍牙互相傳數據(即一個發一個收),bluecove這個開源組件已經把數據讀取都封裝成InputStream了,也就至關於平時的IO讀取了,很天然就使用起readLine()來了。spa
發數據:.net
讀數據:orm
上面是代碼的節選,使用這段代碼會發現寫數據時每次都成功,而讀數據側卻一直沒有數據輸出(除非把流關掉)。通過折騰,原來這裏面有幾個大問題須要理解:blog
readLine()的實質(下面是從JDK源碼摘出來的):ip
從上面看出,readLine()是調用了read(char[] cbuf, int off, int len) 來讀取數據,後面再根據"/r"或"/n"來進行數據處理。
public String readLine() throws IOException
This method returns a string that contains a line of text from a text file. /r, /n, and /r/n are assumed to be line breaks and are not included in the returned string. This method is often used when reading user input from System.in, since most platforms only send the user's input to the running program after the user has typed a full line (that is, hit the Return key).
readLine() has the same problem with line ends that DataInputStream's readLine() method has; that is, the potential to hang on a lone carriage return that ends the stream . This problem is especially acute on networked connections, where readLine() should never be used.
小結,使用readLine()必定要注意:
之前學習的時候也沒有太在乎,在項目中使用到了才發現呵呵
1.讀取一個txt文件,方法不少種我使用了字符流來讀取(爲了方便)
FileReader fr = new FileReader("f:\\TestJava.Java");
BufferedReader bf = new BufferedReader(fr);
//這裏進行讀取
int b;
while((b=bf.read())!=-1){
System.out.println(bf.readLine());
}
發現每行的第一個字符都沒有顯示出來,緣由呢:b=bf.read())!=-1 每次都會先讀取一個字節出來,因此後面的bf.readLine());
讀取的就是每行少一個字節
因此,應該使用
String valueString = null; while ((valueString=bf.readLine())!=null){ System.out.println(valueString); }