public String readUtil(Reader r, String ends) throws IOException {
// 缓存各种变量
StringBuilder sb = new StringBuilder();
int endSize = ends.length();
char endChar = ends.charAt(endSize-1);
char[] buf = new char[1];
int len;
int sbLen;
while (true) {
len = r.read(buf);
if (len == -1)
break;
if (len == 0)
continue;
sb.append(buf[0]);
sbLen = sb.length();
// 如果读取到结束字符串的最后一个字符,那么匹配一下.事实上是endsWith的优化版本,避免生成大字符串
if (buf[0] == endChar && sbLen > endSize) {
String tmp = sb.substring(sbLen - endSize);
if (tmp.equals(ends)) {
return sb.substring(0, sbLen - endSize);
}
}
}
return null;
}
0 回复
添加回复
请先登陆