NutzCN Logo
短点 从流读取到指定结束字符串_eb902049
发布于 2813天前 作者 wendal 1538 次浏览 复制 上一个帖子 下一个帖子
标签:

查看完整内容

    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 回复
添加回复
请先登陆
回到顶部