今天看到项目大神写了一个我之前没有见过的方法,很是简练:
IOUtils.copy(inputStream,outputStream);
比起流和字节间的多行语句,这个迅速吸引了我的注意,开始学习
apache.commons.io.IOUtils
org.apache.poi.util.IOUtils
两种大同小异,这里以第一种为例。
这里有一篇文档写的非常好,https://blog.csdn.net/zhoushou6/article/details/80292271
这里我把需要对比的内容复制过来
(一)打印流中信息
原始做法:new byte[] + .read() + new String()
File f = new File(filename);
InputStream in = new FileInputStream(f);
byte[] b = new byte[1024];
in.read(b);
System.out.println(new String(b));
使用IOUtils,直接减少了咱们byte数组对象以及字节数组转化字符串这个大步骤
File f = new File(filename);
InputStream in = new FileInputStream(f);
System.out.println(IOUtils.toString(in));
(二)流之间的内容复制
原始状态:被复制文件必须先转化为比byte[],再将字节数组作为中间媒介进行二次写入复制文件中
File f = new File(fileName1);
File f2 = new File(fileName2);
InputStream in=new FileInputStream(f);
byte[] byteArray= new byte[1024];
while(in.read()){
in.read(byteArray);
}
OutputStream outputStream = new FileOutputStream(f2);
outputStream.write(byteArray);
IOUtils:
如果是很大的数据,那么可以选择用copyLarge方法,适合拷贝较大的数据流,比如2G以上
File file1 = new File(fileName1);
File file2 = new File(fileName2);
InputStream inputStream2 = new FileInputStream(file2);
OutputStream outputStream1 = new FileOutputStream(file1);
IOUtils.copy(inputStream2,outputStream1);
(三)写入流内容
IOUtils:
IOUtils.write(“我们是幸运哒”, out);
(四)关闭流
原始状态:必要进行判断、关流、异常捕捉
try{
if(inputStream != null){
inputStream.close();
}
}catch(IOException e){
}
IOUtils:
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
(五)整体内容
public static void main(String[] args){
File file1 = new File("jingjing.txt");
File file2 = new File("xinxin.txt");
String str = "连我生日都记不住";
try{
OutputStream outputStream = new FileOutputStream(file2);
outputStream.write(str.getBytes());
InputStream inputStream2 = new FileInputStream(file2);
OutputStream outputStream1 = new FileOutputStream(file1);
IOUtils.copy(inputStream2,outputStream1);
IOUtils.closeQuietly(inputStream2);
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(outputStream1);
}catch (Exception e){
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
THE END
GOOD LUNCK