上面两章介绍了字节流和字符流,这里总结一下IO异常的处理。
1.7前处理
格式:
try{
//业务内容
}catch(IOException e){
//异常处理
}finally{
//关流
}
图片拷贝代码:
package IoStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class InOutputStream {
public static void main(String[] args){
FileInputStream in=null;
FileOutputStream out=null;
try {
//1.创建输入输出流
in = new FileInputStream("dir/1.png");
out = new FileOutputStream("tager/2.png");
//2.边读边写
byte [] buf = new byte[1024];
int len;
while ((len=in.read(buf))!=-1){
out.write(buf,0,len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//3.关流
try {
if(out!=null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(in!=null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
代码相对比较冗余...
1.7的处理
jdk7中出现了一个接口叫做:AutoCloseable 无论是字节流还是字符流都实现了这个接口
格式:
try(流对象;流对象;...){
//业务内容
//自动关流
}catch(IOException e){
//异常处理
}
图片拷贝代码修改:
package IoStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOExcepitonTest {
public static void main(String[] args) {
try (//1.创建输入输出流
FileInputStream in = new FileInputStream("dir/1.png");
FileOutputStream out = new FileOutputStream("tager/2.png")) {
//2.边读边写
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
//3.自动关流
} catch (Exception e) {
//4.异常处理
e.printStackTrace();
}
}
}