美文网首页
JAVA NIO 读取文件并print

JAVA NIO 读取文件并print

作者: Minstrel_a7ca | 来源:发表于2018-07-16 14:33 被阅读0次

Um

造了个轮子,InputStreamReader 也是这样实现的。。。
读取文件应用了NIO的一些类。。。
主要时对ByteBuffer的一些操作

要点

1.CharsetDecoderdecode public final CoderResult decode(ByteBuffer in, CharBuffer out, boolean endOfInput)方法,其中boolean endOfInput指定了是否后有后文。
2.ByteBuffercompact(),将未get的数据放到开头,下一次写入是在其后添加新数据,
具体实现,将下标在[postion,limt)复制到开头,并将limt设置为postion
3.CharBuferclear()

public class ReadFile {
    static final String encode = "UTF-8";
    static final CharsetDecoder cd = Charset.forName(encode).newDecoder();
    public static void main(String[] args) throws Exception {
        FileChannel channel = new FileInputStream(new File("1.txt")).getChannel();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        CharBuffer cBuf = CharBuffer.allocate(1024);
        int bytesRead = channel.read(buf);
        StringBuilder sb = new StringBuilder();
        int length = 0;
        while (bytesRead != -1) {
            buf.flip();
          //指定未完待续
            cd.decode(buf, cBuf, false);
            cBuf.flip();
            length += cBuf.limit();
            //打印出来
            System.out.print(new String(cBuf.array(),0,cBuf.limit()));
            cBuf.clear();       
            buf.compact();
            bytesRead = channel.read(buf);
        }
        //文件包含的字符长度
        System.out.println(length);
    }
}

相关文章

网友评论

      本文标题:JAVA NIO 读取文件并print

      本文链接:https://www.haomeiwen.com/subject/elhbpftx.html