讲之前先说一下可变参数(方法的参数不限制)
举个例子
public static void main(String[] args) {
//文件到文件
f(1,2,3,4,5,6,7);
}
public static void f(int ...i) {//变量类型 ... 变量
for(int p:i) {
System.out.println(p);
}
}
工具类 copy close
public static void copy(InputStream in ,OutputStream os) {//copy 复制
try {
//操作
byte [] flush = new byte [1024];
int len =-1;
while((len=in.read(flush))!=-1) {
os.write(flush, 0, flush.length);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//释放资源
try {
if(null!=os) {
os.close();
}
} catch (Exception e) {
// TODO: handle exception
}
try {
if(null!=in) {
in.close();
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void close(Closeable ...i) {// 释放资源
for(Closeable o:i) {
if(null!=o) {
try {
o.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
try …with…resource类(释放资源)
public static void copy(InputStream in ,OutputStream os) {
try (in:os){//try ...with...resource 会自动释放资源
//操作
byte [] flush = new byte [1024];
int len =-1;
while((len=in.read(flush))!=-1) {
os.write(flush, 0, flush.length);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}