代码改变世界

异常

2018-11-19 00:13  YELLOWHYH  阅读(128)  评论(0编辑  收藏  举报

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,请重新输入文件名,然后尝试重新打开。 如果是其他异常则提示打开或读取文件失败!
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        byte[] content = null;
        FileInputStream fis = null;
        int bytesAvailabe;
        try {
            fis = new FileInputStream("testfis.txt");
            bytesAvailabe = fis.available();// 获得该文件可用的字节数
            if (bytesAvailabe > 0) {
                content = new byte[bytesAvailabe];// 创建可容纳文件大小的数组
                fis.read(content);// 将文件内容读入数组
            }

        } catch (FileNotFoundException e) {
            System.out.println("找不到文件testfis.txt,请重新输入文件名");
        } catch (IOException e) {
            System.out.println("打开或读取文件失败!");
        } finally {
            try {
                System.out.println("关闭文件ing");
                if (fis != null)
                    fis.close();
            } catch (FileNotFoundException e) {
                System.out.println("关闭文件失败!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(Arrays.toString(content));// 打印数组内容
        }
    }
}

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

 

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

答:

操作:关闭资源的操作

 

原因:当程序发生异常时,抛出异常之后的代码不会被执行,如果在发生异常前程序开启了相关资源,则代码可能无法正确关闭资源,而finally的语句块代码都会被执行,所以可以使用finally来释放资源。

 

注意:

 

1.首先要判断是否为null

2.即使是在关闭资源的时候也可能产生异常,需要捕获。

 

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

 

import java.io.FileInputStream;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        byte[] content = null;
        try (FileInputStream fis = new FileInputStream("testfis.txt")) {
            int bytesAvailabe = fis.available();// 获得该文件可用的字节数
            if (bytesAvailabe > 0) {
                content = new byte[bytesAvailabe];// 创建可容纳文件大小的数组
                fis.read(content);// 将文件内容读入数组
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(Arrays.toString(content));
    }
}

 

好处:使用上述代码实现自动关闭资源可以减少代码量,并且避免了在关闭时产生的其它异常。

7. 读取文件并组装对象

7.1 给出关键代码(需出现你的学号)。额外要求:捕获异常时,将错误的信息按照出错原因:行号:该行内容格式输出。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;
class User {
    String name;
    String id;
    String gender;
    int age;
    String address;
    public User(String name, String id, String gender, int age, String address) {
        super();
        this.name = name;
        this.id = id;
        this.gender = gender;
        this.age = age;
        this.address = address;
    }
}

public class Test {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(new File("身份证号.txt"));
        ArrayList<User> list = new ArrayList<>();
        int num = 0;
        String line = null;
        while (in.hasNextLine()) {
            try {
                line = in.nextLine();// 读出myfile.txt的下一行
                num++;
                Scanner lineScanner = new Scanner(line);// 为每一行建立一个扫描器
                // System.out.println("lineScanner="+lineScanner);
                lineScanner.useDelimiter(" ");// 使用空格作为分隔符
                // System.out.println(line);
                String a1 = lineScanner.next();// 姓名
                String a2 = lineScanner.next();// 身份证号
                String a3 = lineScanner.next();// 性别
                String a4 = lineScanner.next();// 年龄
                String a5 = lineScanner.next();// 地址
                while (lineScanner.hasNext()) {// 谨防地址只有一段
                    a5 += lineScanner.next();
                }
                list.add(new User(a1, a2, a3, Integer.parseInt(a4), a5));
                System.out.println(a1 + " " + a2 + " " + a3 + " " + a4 + " " + a5);
            } catch (NoSuchElementException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) { // 字符转换为整数异常捕获
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println(e + "错误出现在文件的第" + num + "行,为:" + line);
            }
        }

    }

}

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

 

答:尝试将所有出错信息存入文件中。