java 输入输出IO流 IO异常处理try(IO流定义){IO流使用}catch(异常){处理异常}finally{死了都要干}
IO异常处理
之前我们写代码的时候都是直接抛出异常,但是我们试想一下,如果我们打开了一个流,在关闭之前程序抛出了异常,那我们还怎么关闭呢?这个时候我们就要用到异常处理了。
try-with-resource语句: 确保在异常出现后 打开的流能自动关闭,无需单独再写.close()流关闭语句。
语法:
try(构建流通道语句){
业务处理逻辑
}catch(异常){
异常处理逻辑
}finally{
....
}
示例代码:
import java.io.*; import java.nio.charset.Charset; /** * @ClassName FileCopyTryCatchExample * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/17. */ public class FileCopyTryCatchExample { public static void main(String[] args){ String srcPath = "C:\\Users\\ZHANGMINGDA\\Pictures\\康熙北巡.jpg"; String dstpath = "C:\\Users\\ZHANGMINGDA\\Pictures\\康熙北巡bak.jpg"; char[] tmpchars = new char[1024]; int readLength; // try(Reader fileReader = new FileReader(srcPath); Writer fileWriter = new FileWriter(dstpath)){ try(Reader fileReader = new MyFileReader(srcPath); Writer fileWriter = new MyFileWriter(dstpath)){ while ((readLength = fileReader.read(tmpchars)) != -1){ fileWriter.write(tmpchars,0,readLength); } // fileReader.close(); // fileWriter.close(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { System.out.println("done"); } }
//测试try(构建流)语句是否自动关闭流,重写FileReader和FileWriter public static class MyFileReader extends FileReader{ public MyFileReader(String fileName) throws FileNotFoundException { super(fileName); } public MyFileReader(File file) throws FileNotFoundException { super(file); } public MyFileReader(FileDescriptor fd) { super(fd); } public MyFileReader(String fileName, Charset charset) throws IOException { super(fileName, charset); } public MyFileReader(File file, Charset charset) throws IOException { super(file, charset); } @Override public void close() throws IOException { super.close(); System.out.println("关闭了输入流"); } } public static class MyFileWriter extends FileWriter { public MyFileWriter(String fileName) throws IOException { super(fileName); } public MyFileWriter(String fileName, boolean append) throws IOException { super(fileName, append); } public MyFileWriter(File file) throws IOException { super(file); } public MyFileWriter(File file, boolean append) throws IOException { super(file, append); } public MyFileWriter(FileDescriptor fd) { super(fd); } public MyFileWriter(String fileName, Charset charset) throws IOException { super(fileName, charset); } public MyFileWriter(String fileName, Charset charset, boolean append) throws IOException { super(fileName, charset, append); } public MyFileWriter(File file, Charset charset) throws IOException { super(file, charset); } public MyFileWriter(File file, Charset charset, boolean append) throws IOException { super(file, charset, append); } @Override public void close() throws IOException { super.close(); System.out.println("关闭了输出流"); } } }
posted on 2021-04-17 22:09 zhangmingda 阅读(592) 评论(0) 编辑 收藏 举报