可以计算长度的OutputStream

可以计算长度的OutputStream

欢迎大家关注Android开源网络框架NoHttp:https://github.com/yanzhenjie/NoHttp
在线直播视频和代码下载:http://pan.baidu.com/s/1miEOtwG

版权声明:转载请注明本文转自严振杰的CSDN博客: http://blog.csdn.net/yanzhenjie1003

QQ交流群1:46523908
QQ交流群2:46505645
群资源非常有限,请先加群1,如果群1满再加群2,谢谢。

前言

  这几天在写NoHttp的时候遇到需要从统计发送包体的长度,我的包体内容全部用OutpuStream写出去,所以很难统计长度,所以这里我继承OutputStream写了一个可以统计长度的OutputStream

实现

  觉得没什么好说的,就是继承OutputStream

public class CounterOutputStream extends OutputStream {

    private final AtomicLong length = new AtomicLong(0L);

    public CounterOutputStream() {
    }

    public void write(long count) {
        if (count > 0)
            length.addAndGet(count);
    }

    public long get() {
        return length.get();
    }

    @Override
    public void write(int oneByte) throws IOException {
        length.addAndGet(oneByte);
    }

    @Override
    public void write(byte[] buffer) throws IOException {
        length.addAndGet(buffer.length);
    }

    @Override
    public void write(byte[] buffer, int offset, int count) throws IOException {
        length.addAndGet(count);
    }

    /** * Didn't do anything here. * * @throws IOException nothing. */
    @Override
    public void close() throws IOException {
    }

    /** * Didn't do anything here. * * @throws IOException nothing. */
    @Override
    public void flush() throws IOException {
    }
}

使用

  其实和普通的流没啥区别的:

CounterOutputStream counterOutputStream = new CounterOutputStream();

...// 这里和普通流一样写入就好了

long outputLength = counterOutputStream.get();

欢迎大家关注Android开源网络框架NoHttp:https://github.com/yanzhenjie/NoHttp
在线直播视频和代码下载:http://pan.baidu.com/s/1miEOtwG
  

你可能感兴趣的:(可以计算长度的OutputStream)