1.泛型 2.参数 3.JDK1.7写法 public class TestCloseStream {
public static void main(String[] args) {
}
//1.7新特性try-with-resousce ,实质还是try{}catch
public static void closeStream() throws Exception{
File src = new File("E:/workspace/images/bg.jpg");
File dest = new File("E:/workspace/images/bg11.jpg");
InputStream is = null;
OutputStream os = null;
try(
is = new BufferedInputStream(new FileInputStream(src));
os = new BufferedOutputStream(new FileOutputStream(dest));
){
byte[] car = new byte[1024];
int len =0;
while(-1 != (len = is.read(car))){
os.write(car);
}
os.flush();
os.close();
is.close();
}
}
//使用泛型
public static void closeAll(T...io){
for(Closeable temp:io){
if(null != temp){
try {
temp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//可变参数:只能是形参最后一个参数, 处理方式跟数组一致
public static void close(Closeable...io){
for(Closeable temp:io){
if(null != temp){
try {
temp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}