比如需要判断一个串是否结束 12345/n/n 用两个 /n 来判断结束。
通常一开始都会这么写
while( br.readLine()!=null ) {
// dosomething
}
但是会发现这样永远也不会结束退出,因为跟读文本的时候不一样。后面仔细读 API 发现描述是
-
返回:
- 包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
Reads a line of text. A line is considered to be terminated by any one of a line feed ('/n'), a carriage return ('/r'), or a carriage return followed immediately by a linefeed.
-
Returns:
- A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
也就是说要到达流的末尾,才会null,看源码:
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
仅有流到达末尾,才能返回null,而socket的流本来就是趋于无限的,根本不知道何时才会结尾,所以条件永远都满足不了。
因此不能用 null 来判串,而要用空串来判断
String str=null;
do{
str=br.readLine();
// dosomething
}while( !"".equals( str ) );
写出来备忘下,我也没仔细读API,自以为是的以为跟文件流结束差不多。悔恨,不知道有多少人会犯同样的错误呢。