IOUtils工具类简介及应用

版权声明:本文为博主原创文章,转载请注明作者和出处,如有错误,望不吝赐教。 https://blog.csdn.net/weixin_41888813/article/details/85043720

以前写文件的复制很麻烦,需要各种输入流,然后读取line,输出到输出流...其实apache.commons.io里面提供了输入流输出流的常用工具方法,非常方便。下面就结合源码,看看IOUTils都有什么用处吧!

copy

源码介绍:这个方法可以拷贝流,算是这个工具类中使用最多的方法了。支持多种数据间的拷贝

copy(inputstream,outputstream)
copy(inputstream,writer)
copy(inputstream,writer,encoding)
copy(reader,outputstream)
copy(reader,writer)
copy(reader,writer,encoding)

 copy内部使用的其实还是copyLarge方法。因为copy能拷贝Integer.MAX_VALUE的字节数据,即2^31-1。

copyLarge

源码介绍:这个方法适合拷贝较大的数据流,比如2G以上。

copyLarge(reader,writer) 默认会用1024*4的buffer来读取
copyLarge(reader,writer,buffer)

 第二个内部的细节可以参考:

 public static long copyLarge(Reader input, Writer output, char [] buffer) throws IOException {
        long count = 0;
        int n = 0;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

这个方法会用一个固定大小的Buffer,持续不断的读取数据,然后写入到输出流中。 

toBufferedInputStream 

源码介绍:把流的全部内容放在另一个流中 

    public static InputStream toBufferedInputStream(InputStream input) throws IOException {
        return ByteArrayOutputStream.toBufferedInputStream(input);
    }

    public static InputStream toBufferedInputStream(InputStream input, int size) throws IOException {
        return ByteArrayOutputStream.toBufferedInputStream(input, size);
    }

实际应用

InputStream in = classPathResource.getInputStream();

InputStream inputStream = IOUtils.toBufferedInputStream(in);

参考来源于:

http://www.cnblogs.com/xing901022/p/5978989.html

猜你喜欢

转载自blog.csdn.net/weixin_41888813/article/details/85043720