zoukankan      html  css  js  c++  java
  • 读文件Io异常的处理

    1、首先你要阻止后边的代码执行,而且需要通知调用者这里出错了!使用 throw 处理

    2、仅仅抛出异常,方法上要声明,调用者也必须处理。把Ioexception传递给RuntimeException包装一层,然后再抛出,这样做是为了让调用者使用灵活

    RuntimeException:不用在方法上声明抛出。

    package cn.lyjs.exception;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class Demo1 {
        public static void main(String[] args) {
            readTest();
        }
        
        public static void readTest(){
            FileInputStream fileInputStream=null;
            try {
                //找到目标文件
                File file=new File("E:\aaadda.txt");
                //建立数据输入管道
                fileInputStream=new FileInputStream(file);
                int length=0;
                //建立缓冲数组读取数据
                byte [] buf=new byte[1024];
                while((length=fileInputStream.read(buf))!=-1){
                    System.out.print(new String(buf,0,length));
                }
            } catch (IOException e) {
                //处理的代码...首先你要阻止后边的代码执行,而且需要通知调用者这里出错了
                //throw new RuntimeException(e); 把Ioexception传递给RuntimeException包装一层,然后再抛出,这样做是为了让调用者使用灵活
                System.out.println("读取文件失败...");
                throw new RuntimeException(e);
            }finally{
                try {
                    if(fileInputStream!=null){
                        fileInputStream.close();
                    }
                } catch (IOException e) {
                    System.out.println("关闭资源失败了");
                    throw new RuntimeException(e);
                }
            }
            
        }
    }
  • 相关阅读:
    分布式缓存系统Memcached
    HTTP(GET/POST)请求过程中的编码问题
    将指定的Json字符串转为指定的T类型对象(转帖)
    Linux 中有几个文件压缩和解压缩工
    策略添加-通过域策略组自动映射共享文件夹
    Centos 7 加AD域
    Gns3 模拟器创建VLAN
    防火墙常用命令
    Centos 6 任务计划配置
    Cenots 7 开启 SSH_远程连接
  • 原文地址:https://www.cnblogs.com/lyjs/p/4999930.html
Copyright © 2011-2022 走看看