• 第12周预习作业


    6.为如下代码加上异常处理

    byte[] content = null;
    FileInputStream fis = new FileInputStream("testfis.txt");
    int bytesAvailabe = fis.available();//获得该文件可用的字节数
    if(bytesAvailabe>0){
        content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
        fis.read(content);//将文件内容读入数组
    }
    System.out.println(Arrays.toString(content));//打印数组内容

    6.1 改正代码,并增加如下功能。当找不到文件时,需提示用户找不到文件xxx,请重新输入文件名,然后尝试重新打开。 如果是其他异常则提示打开或读取文件失败!

    注1:里面有多个方法均可能抛出异常。
    功能2:需要添加finally关闭文件。无论上面的代码是否产生异常,总要提示关闭文件ing。如果关闭文件失败,提示关闭文件失败!

    //修改后的代码
    byte[] content = null;
            Scanner sc = new Scanner(System.in);
            FileInputStream fis = null;
            while (sc.hasNext()) {
                String str = sc.next();
                try {
                    fis = new FileInputStream(str);
                    int bytesAvailabe = fis.available();// 获得该文件可用的字节数
                    if (bytesAvailabe > 0) {
                        content = new byte[bytesAvailabe];// 创建可容纳文件大小的数组
                        fis.read(content);// 将文件内容读入数组
                    }
                    System.out.println(Arrays.toString(content));// 打印数组内容
                } catch (Exception e) {
                    if (e instanceof FileNotFoundException) {
                        System.out.println("找不到文件" + str + ",请重新输入文件名");
                    } else {
                        System.out.println("打开或读取文件失败!");
                        break;
                    }

    6.2 结合题集6-2代码,要将什么样操作放在finally块?为什么?使用finally关闭资源需要注意一些什么?

    //添加finally模块
    finally {
                    try {
                        fis.close();
                        System.out.println("关闭文件ing");
                    } catch (Exception e) {// 判断是否是空指针异常
                        System.out.println(e);
                    }
    
                }

    try{}catch{}放入finally中,因为关闭文件可能存在异常。

    6.3 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源。简述这种方法有何好处?

    //利用try-with-resorce
    try (FileInputStream fis = new FileInputStream("testfis.txt")) {// 在try的圆括号中写入将要关闭资源的对象
                int bytesAvailabe = fis.available();// 获得该文件可用的字节数
                if (bytesAvailabe > 0) {
                    content = new byte[bytesAvailabe];// 创建可容纳文件大小的数组
                    fis.read(content);// 将文件内容读入数组
                }
            } catch (Exception e) {
                System.out.println(e);
            } 

    尝试自动关闭资源的对象生成写在try之后的圆括号中,无需判断是否为null,也避免了在关闭时产生的其它异常,使整个代码更简洁。try执行完后文件即被关闭。

    7. 读取文件并组装对象

    实验任务书中的题目3:读取文件并组装对象
    7.1 给出关键代码(需出现你的学号)。额外要求:捕获异常时,将错误的信息按照出错原因:行号:该行内容格式输出。

    class User  {//用户类
        String name;
        String id;
        String gender;
        String address;
        int age;
    }
    //利用自动生成功能增加有参构造函数,set/getter方法,toString方法
    //学号201721123070
    public
    class browse {// 浏览文本数据 private static Scanner in; public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<User> student = new ArrayList<User>(); try { int count = 0; Scanner sc = new Scanner(new File("D:/身份信息.txt")); while (sc.hasNextLine()) { String line = sc.nextLine(); count++; Scanner lineScanner = new Scanner(line);// 为每一行建立一个扫描器 lineScanner.useDelimiter(" ");// 调用reset()方法将分隔符设为默认 try { String a1 = lineScanner.next();// 姓名 String a2 = lineScanner.next();// 身份证号 String a3 = lineScanner.next();// 性别 String a4 = lineScanner.next();// 年龄 String a5 = lineScanner.next();// 地址 if(a1.length()==0&&a2.length()==0&&a4.length()==0&&a3.length()==0&&a5.length()==0) throw new Exception("文件中无信息"); try { if (a1.length() == 0 ) throw new Exception("姓名为空"); if (a2.length() == 0 || a2.length() != 18) throw new Exception("身份证号格式错误"); if (a3.length() == 0 ) throw new Exception("性别未填写"); if (!a3.equals("男") && !a3.equals("女")) throw new Exception("性别格式错误"); if (a4.length() == 0 ) throw new Exception("地址未填写"); if (a5.length() == 0 ) throw new Exception("年龄未填写"); User user = new User(a1, a2, a3, a4, Integer.parseInt(a5)); student.add(user); System.out.println(a1 + a2 + a3 + a4 + a5); } catch (Exception e) { System.out.println(e + ":" + count + ":" + line); } } catch (Exception e) { System.out.println(e + ":" + count + ":" + line); } } } catch (FileNotFoundException e) { System.out.println(e); } Collections.sort(student, (User o1, User o2) -> { return o1.getAge() - o2.getAge(); }); for (User user : student) { System.out.println(user.toString()); } }
    //测试数据
    A同学 362409188809234578 女 安徽省安庆市 18
     362409188809234578 女 江西省南昌市 20
    C同学 3624091888092345x 男 湖北省武汉市 19
    D同学 362409188809234578  福建省厦门市 24
    E同学 362409188809234578 女 安徽省安庆市 18
    F同学 562378324738247213 男 北京市 
    G同学 121329323492149210 女 广西省壮族自治区 45
    H同学 124728473291948321 男 广东省广州市 38
    I同学 237489278578174827 男  29
    

      

    //运行结果
    A同学362409188809234578女安徽省安庆市18
    java.util.NoSuchElementException:2: 362409188809234578 女 江西省南昌市 20
    java.lang.Exception: 身份证号格式错误:3:C同学 3624091888092345x 男 湖北省武汉市 19
    java.lang.Exception: 性别未填写:4:D同学 362409188809234578  福建省厦门市 24
    E同学362409188809234578女安徽省安庆市18
    java.util.NoSuchElementException:6:F同学 562378324738247213 男 北京市 
    G同学121329323492149210女广西省壮族自治区45
    H同学124728473291948321男广东省广州市38
    java.lang.Exception: 地址未填写:9:I同学 237489278578174827 男  29
    User [name=A同学, id=362409188809234578, gender=女, address=安徽省安庆市, age=18]
    User [name=E同学, id=362409188809234578, gender=女, address=安徽省安庆市, age=18]
    User [name=H同学, id=124728473291948321, gender=男, address=广东省广州市, age=38]
    User [name=G同学, id=121329323492149210, gender=女, address=广西省壮族自治区, age=45]

    7.2 如果文件有上万行文本,出错的信息可能有很多行,如果将出错信息直接输出到控制台容易被忽略,请问如何解决?

    由输出控制台改为直接输出
  • 相关阅读:
    【转】Spring高级进阶:BeanFactoryPostProcessor
    【转】2019版本idea导入新spring boot项目有关配置讲解及右侧没有maven解决方式
    jquery 选择器(name,属性,元素)大全
    【转】读懂正则表达式就这么简单
    【转】跨站脚本攻击(XSS)
    Oracle 分页查询 插叙不出数据
    spring:过滤器和拦截器
    Idea-每次修改JS文件都需要重启Idea才能生效解决方法 热部署
    IDEA: Call Hierarchy
    Linux之文件读取查看之cat、head、tail、tac、rev、more、less
  • 原文地址:https://www.cnblogs.com/huyaoco/p/9980769.html
Copyright © 2020-2023  润新知