java ioutils 写入文件_文件输入输出流工具: IOUtils使用总结

序言

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

常用的静态变量

在IOUtils中还是有很多常用的一些变量的,比如换行符等等

public static final char DIR_SEPARATOR_UNIX = '/';

public static final char DIR_SEPARATOR_WINDOWS = '\\';

public static final char DIR_SEPARATOR;

public static final String LINE_SEPARATOR_UNIX = "\n";

public static final String LINE_SEPARATOR_WINDOWS = "\r\n";

public static final String LINE_SEPARATOR;

static {

DIR_SEPARATOR = File.separatorChar;

StringBuilderWriter buf = new StringBuilderWriter(4);

PrintWriter out = new PrintWriter(buf);

out.println();

LINE_SEPARATOR = buf.toString();

out.close();

}

常用方法

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,持续不断的读取数据,然后写入到输出流中。

read

从一个流中读取内容

read(inputstream,byte[])

read(inputstream,byte[],offset,length)

//offset是buffer的偏移值,length是读取的长度

read(reader,char[])

read(reader,char[],offset,length)

这里我写了个小例子,可以测试read方法的效果:

@Test

public void readTest(){

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值