FileUtils
封装拷贝
public static void copy(InputStream is,OutputStream os) {
try {
byte[] flush = new byte[1024];
int len = -1;
while((len=is.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
close(is,os);
}
}
封装释放
public static void close(Closeable... ios) {
for(Closeable io:ios) {
try {
if(null!=io) {
io.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试
public static void main(String[] args) {
try {
InputStream is = new FileInputStream("abc.txt");
OutputStream os = new FileOutputStream("abc-copy.txt");
copy(is,os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] datas = null;
try {
InputStream is = new FileInputStream("p.png");
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("p-copy.png");
copy(is,os);
} catch (IOException e) {
e.printStackTrace();
}
}