1.io流手动关闭
每个io流执行完毕以后,都会从下到上,依次调用close();方法。
public class Demo3 {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:/aaa/22.png"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:/bbb/xixi.png"));
byte[] buf = new byte[4 * 1024];
int length;
while ((length = bis.read(buf)) != -1) {
bos.write(buf, 0, length);
}
bos.close();
bis.close();
}
}
2.用异常处理
jdk1.7以后,try--catch自动关闭流,不需要手动关闭。主要因为,try--catch自动把流的异常给关闭。
public class Demo1 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E:\\11.jpg");
fos = new FileOutputStream("D:\\encohe.jpg");
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes1 = new byte[4 * 1024];
int temp;
while ((temp = bis.read(bytes1)) != -1) {
bos.write(bytes1,0, temp);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}