编程语言
首页 > 编程语言> > 廖雪峰Java6 IO编程-2input和output-4Filter模式

廖雪峰Java6 IO编程-2input和output-4Filter模式

作者:互联网

1.JDK提供的InputStream分为两类:

//演示代码
InputStream input = new GZIPInputStream(//直接读取解压缩包的内容
    new BufferedInputStream(//提供缓冲的功能
    new FileInputStream("test.gz"))); 



廖雪峰示例中的CountInputStream有错误,当读取完毕后,返回-1,而count再读取完毕后,会减1,导致结果不一样。运行结果如下。只需要将count的初始值设置为1即可。

public class CountInputStream extends FilterInputStream {
    int count=0;
    public CountInputStream(InputStream in) {
        super(in);
    }
    //重写read方法,使用count计数
    public int read(byte[] b,int off,int len) throws IOException {
        int n = super.read(b,off,len);
        count += n;
        System.out.println(count);
        return n;//最后返回-1,count-1
    }
}
public class Main {
    static void printCount1(List<Integer> list) throws IOException{
        try(InputStream input = new GZIPInputStream(
                        new BufferedInputStream(
                                new FileInputStream("./src/main/java/com/testList/test.gz")))){
            byte[] buffer = new byte[1024];//创建竹筒
            int count=0;
            int n ;
            while((n=input.read(buffer))!=-1){
                count += n;
                list.add(n);
            }
            System.out.println("直接读取的和:"+count);
            System.out.println("直接读取得到的集合的和"+getSum(list));
        }
    }
    static void printCount2(List<Integer> list) throws IOException{
        try(CountInputStream input = new CountInputStream(
                new GZIPInputStream(
                        new BufferedInputStream(
                                new FileInputStream("./src/main/java/com/testList/test.gz"))))){
            byte[] buffer = new byte[1024];
            int n;
            while((n=input.read(buffer))!=-1){
                list.add(n);
//                System.out.println();
            }
            System.out.println("通过CountInputStream获取的和:"+input.count);
            System.out.println("通过CountInputStream获取的集合的和:"+getSum(list));
        }
    }
    static Integer getSum(List<Integer> list){
        int sum = 0;
        for(int i=0;i<list.size();i++){
            sum += list.get(i);
        }
        return sum;
    }
    public static void main(String[] args) throws IOException {
        List<Integer> list1 = new LinkedList<>();
        List<Integer> list2 = new LinkedList<>();
        printCount2(list2);
        printCount1(list1);
        //从结果
        System.out.println(list1);
    }
}

2.总结

标签:count,int,list,println,Java6,IO,FileInputStream,2input,new
来源: https://www.cnblogs.com/csj2018/p/10659414.html