日志文章

2019-12-23 aflfte2011

拷贝的封装与资源释放方法

package com.aflfte.IO;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 1、封装拷贝
 * 2、封装释放资源
 * @author jinhao
 *
 */
public class FileUtils {

public static void main(String[] args) {
//文件到文件
/*try {
InputStream is=new FileInputStream("f:/jinhao/Desktop/11.jpg");
OutputStream ou=new FileOutputStream("123.jpg");
Copy(is, ou);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}*/
//文件到字节数组
byte[] datas=null;
try {
InputStream is=new FileInputStream("f:/jinhao/Desktop/11.jpg");
ByteArrayOutputStream ou=new ByteArrayOutputStream();
Copy(is, ou);
datas=ou.toByteArray();
System.out.println(datas.length);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//字节数组到文件
try {
InputStream is=new ByteArrayInputStream(datas);
OutputStream ou=new FileOutputStream("223.jpg");
Copy(is, ou);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}

}
public static void Copy(InputStream in,OutputStream ou) {
try(in;ou) {//加入输入输出流就可自动释放资源
byte[] inb=new byte[1024];
int len=-1;
while((len=in.read(inb))!=-1) {
ou.write(inb,0,len);
ou.flush();
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
//释放资源封装
/*
public static void close(InputStream in,OutputStream ou) {
if(ou!=null) {
try {
ou.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(in!=null) {
try {
in.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}

public static void close(Closeable... ios) {
for(Closeable io:ios) {
if(io!=null) {
try {
io.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}*/

}


« IO缓冲流的使用(BufferedInputStream和bufferedOutputstream) | 利用IO字节数组流实现文件拷贝»