Java IO体系之BufferedReader

IO体系图

这里写图片描述

应用

File[] files = new File(destinationPath).listFiles();
long startTime = System.currentTimeMillis();
int num = 0;
for (int i = 0; i < files.length; i++) {
	InputStreamReader inReader = new InputStreamReader(new FileInputStream(files[i]), "GBK");
	BufferedReader bReader = new BufferedReader(inReader);
	contentLine = bReader.readLine();
	while (contentLine != null) {
		// 日志打印
		LOGGER.info("读取的当前数据==》" + contentLine.trim());
		// AES加密
		String encryptContent = AESCoder.encrypt(aesKey, contentLine.trim());
		// 发送到MQTT
		mqttGateway.sendToMqtt(encryptContent, mqttTheme);
		num++;
		// 读取下一行
		contentLine = bReader.readLine();
	}
	// 关闭资源(需写在for循环里)
	bReader.close();
}

简单介绍

Reads text from a character-input stream, buffering characters so as to
provide for the efficient reading of characters, arrays, and lines.

源码

成员方法

private Reader in;

private char cb[];
private int nChars, nextChar;

private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

/** If the next character is a line feed, skip it */
private boolean skipLF = false;

/** The skipLF flag when the mark was set */
private boolean markedSkipLF = false;

private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;

构造函数

public BufferedReader(Reader in, int sz) {
    super(in);
    if (sz <= 0)
        throw new IllegalArgumentException("Buffer size <= 0");
    this.in = in;
    cb = new char[sz];
    nextChar = nChars = 0;
}

public BufferedReader(Reader in) {
    this(in, defaultCharBufferSize);
}

成员方法

/** Checks to make sure that the stream has not been closed */
private void ensureOpen() throws IOException {
    if (in == null)
        throw new IOException("Stream closed");
}

/**
 * Reads a single character.
 */
public int read() throws IOException {
    synchronized (lock) {
        ensureOpen();
        // 无限循环
        for (;;) {
            if (nextChar >= nChars) {
                fill();
                if (nextChar >= nChars)
                    return -1;
            }
            if (skipLF) {
                skipLF = false;
                if (cb[nextChar] == '\n') {
                    nextChar++;
                    continue;
                }
            }
            return cb[nextChar++];
        }
    }
}

public int read(char cbuf[], int off, int len) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if ((off < 0) || (off > cbuf.length) || (len < 0) ||
            ((off + len) > cbuf.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        int n = read1(cbuf, off, len);
        if (n <= 0) return n;
        while ((n < len) && in.ready()) {
            int n1 = read1(cbuf, off + n, len - n);
            if (n1 <= 0) break;
            n += n1;
        }
        return n;
    }
}

/**
 * Reads characters into a portion of an array, reading from the underlying
 * stream if necessary.
 */
private int read1(char[] cbuf, int off, int len) throws IOException {
    if (nextChar >= nChars) {
        if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
            return in.read(cbuf, off, len);
        }
        fill();
    }
    if (nextChar >= nChars) return -1;
    if (skipLF) {
        skipLF = false;
        if (cb[nextChar] == '\n') {
            nextChar++;
            if (nextChar >= nChars)
                fill();
            if (nextChar >= nChars)
                return -1;
        }
    }
    // Returns the smaller of two {@code int} values.
    int n = Math.min(len, nChars - nextChar);
    // 从原数组复制指定长度n到目的数组
    System.arraycopy(cb, nextChar, cbuf, off, n);
    nextChar += n;
    return n;
}

Reads a line of text

public String readLine() throws IOException {
   return readLine(false);
}

String readLine(boolean ignoreLF) throws IOException {
    StringBuffer s = null;
    int startChar;

    synchronized (lock) {
        ensureOpen();
        boolean omitLF = ignoreLF || skipLF;

    bufferLoop:
        for (;;) {

            if (nextChar >= nChars)
                fill();
            if (nextChar >= nChars) { /* EOF */
                if (s != null && s.length() > 0)
                    return s.toString();
                else
                    return null;
            }
            boolean eol = false;
            char c = 0;
            int i;

            /* Skip a leftover '\n', if necessary */
            if (omitLF && (cb[nextChar] == '\n'))
                nextChar++;
            skipLF = false;
            omitLF = false;

        charLoop:
            for (i = nextChar; i < nChars; i++) {
                c = cb[i];
                if ((c == '\n') || (c == '\r')) {
                    eol = true;
                    break charLoop;
                }
            }

            startChar = nextChar;
            nextChar = i;

            if (eol) {
                String str;
                if (s == null) {
                    str = new String(cb, startChar, i - startChar);
                } else {
                    s.append(cb, startChar, i - startChar);
                    str = s.toString();
                }
                nextChar++;
                if (c == '\r') {
                    skipLF = true;
                }
                return str;
            }

            if (s == null)
                s = new StringBuffer(defaultExpectedLineLength);
            s.append(cb, startChar, i - startChar);
        }
    }
}

Skips characters

public long skip(long n) throws IOException {
    if (n < 0L) {
        throw new IllegalArgumentException("skip value is negative");
    }
    synchronized (lock) {
        ensureOpen();
        long r = n;
        while (r > 0) {
            if (nextChar >= nChars)
                fill();
            if (nextChar >= nChars) /* EOF */
                // 结束循环
                break;
            if (skipLF) {
                skipLF = false;
                if (cb[nextChar] == '\n') {
                    nextChar++;
                }
            }
            long d = nChars - nextChar;
            if (r <= d) {
                nextChar += r;
                r = 0;
                break;
            }
            else {
                r -= d;
                nextChar = nChars;
            }
        }
        return n - r;
    }
}


public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值