1、封装拷贝的过程
2、封装释放资源
/**
* 1、封装拷贝过程
* 2、封装释放资源
*/
public static void main(String[] args){
//文件到文件
try {
InputStream is = new FileInputStream("E:\\个人文件夹\\桌面\\456.txt");
OutputStream os = new FileOutputStream("E:\\\\个人文件夹\\\\桌面\\\\456-2.txt");
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
//文件到字节数组
byte[] datas = null;
try {
InputStream is = new FileInputStream("E:\\个人文件夹\\桌面\\timg.jpg");
ByteArrayOutputStream os = new ByteArrayOutputStream();
copy(is, os);
datas = os.toByteArray();
System.out.println(datas.length);
} catch (IOException e) {
e.printStackTrace();
}
//字节数组到文件
try {
InputStream is = new ByteArrayInputStream(datas);
OutputStream os = new FileOutputStream("E:\\个人文件夹\\桌面\\timg22.jpg");
copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
}
//对接输入输出流:封装拷贝过程
public static void copy(InputStream is,OutputStream os) {
try {
//分段读取
byte[] flush = new byte[1024];
int len;
while((len=is.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(is, os);
}
}
//封装释放资源
public static void close(InputStream is,OutputStream os) {
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
}
}
//释放资源
public static void close(Closeable...ios) {
for(Closeable io:ios) {
try {
if (null != io) {
io.close();
}
} catch (IOException e) {
}
}
}
3、jdk1.7使用 try…with…resource
把流的放到try后面的括号中,去掉finally语句块
public static void copy(InputStream is,OutputStream os) {
try (is;os){
//分段读取
byte[] flush = new byte[1024];
int len;
while((len=is.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}