适用于 Scanner 和 BufferedReader 的 try、catch 和 finally 的正确方法。

huangapple go评论90阅读模式
英文:

Proper method for a try, catch, and finally for Scanner and BufferedReader

问题

尝试理解在主方法中针对 Scanner 和 BufferedReader 的最佳和最有效的 try-catch-finally 方法。是应该有两个不同的 catch 块,还是将它们合并为一个?

public static void main(String[] args) throws IOException {
    // 打开文件输入流
    try {
        BufferedReader reader = new BufferedReader(new FileReader("DATABASE.txt"));

        // 逐行读取文件
        String line = null;
        Scanner scan = null;

        BST tree = new BST();
        line = reader.readLine();

        while (line != null) {
            Employee emp = new Employee();
            scan = new Scanner(line);
            scan.useDelimiter(",");

            while (scan.hasNext()) {
                emp.setEmployeeID(Integer.parseInt(scan.next()));
                emp.setFirstName(scan.next());
                emp.setLastName(scan.next());
                emp.setSalary(Double.parseDouble(scan.next()));
                line = reader.readLine();
            }
            tree.insert(emp);
        }
        reader.close();
        tree.inOrder();
        //System.out.println(empList);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
英文:

Trying to understand the best and most efficient way for a try-catch-finally for both the Scanner and BufferedReader in my main method. Should there be two different catches or combine them into one?

    public static void main(String[] args) throws IOException {
    //open file input stream
    try {
        BufferedReader reader = new BufferedReader(new FileReader("DATABASE.txt"));

        //read file line by line
        String line = null;
        Scanner scan = null;

        BST tree = new BST();
        line = reader.readLine();

        while(line != null) {
            Employee emp = new Employee();
            scan = new Scanner(line);
            scan.useDelimiter(",");

            while(scan.hasNext()){
                emp.setEmployeeID(Integer.parseInt(scan.next()));
                emp.setFirstName(scan.next());
                emp.setLastName(scan.next());
                emp.setSalary(Double.parseDouble(scan.next()));
                line = reader.readLine();
            }
            tree.insert(emp);
        }
        reader.close();
        tree.inOrder();
        //System.out.println(empList);
    } catch(IOException e){
        e.printStackTrace();
    }

答案1

得分: 0

一个单独的捕获块应该足够。您可以添加一个finally块,它将关闭阅读器和扫描器实例(如果它们非空)。这样,无论try块是否正常完成或抛出异常,它们都将被关闭。需要添加空值检查,因为try块可能无法达到这两个对象的初始化,因为可能会发生异常。

英文:

A single catch block should be sufficient. You can add a finally block that will close the reader and scanner instances (if they are non null). This way, they will be closed regardless if the try block finishes normally or an exception is thrown. The null checks should be added because the try block might not reach the initialization of both objects, as an exception might occur.

答案2

得分: 0

在 try-catch-finally 代码块之外声明了 Scanner scan = nullBufferedReader reader = null;,并在 try 块内对它们进行了初始化。异常被捕获后它们都会进入 finally 代码块。

public static void main(String[] args) throws IOException {
    Scanner scan = null;
    BufferedReader reader = null;
    // 打开文件输入流
    try {
        reader = new BufferedReader(new FileReader("DATABASE.txt"));

        // 按行读取文件
        String line = null;
        Scanner scan = null;

        BST tree = new BST();
        line = reader.readLine();
        scan = new Scanner(line);
        while (line != null) {
            Employee emp = new Employee();
            scan.useDelimiter(",");

            while (scan.hasNext()) {
                emp.setEmployeeID(Integer.parseInt(scan.next()));
                emp.setFirstName(scan.next());
                emp.setLastName(scan.next());
                emp.setSalary(Double.parseDouble(scan.next()));
                line = reader.readLine();
            }
            tree.insert(emp);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        reader.close();
        scan.close();
    }
}
英文:

Declared Scanner scan = null and BufferedReader reader = null; outside of the try-catch-finally block of code and initialized them inside the try block. The exception gets caught and they both reach the finally block.

public static void main(String[] args) throws IOException {
    Scanner scan = null;
    BufferedReader reader = null;
    //open file input stream
    try {
        reader = new BufferedReader(new FileReader("DATABASE.txt"));

        //read file line by line
        String line = null;
        Scanner scan = null;

        BST tree = new BST();
        line = reader.readLine();
        scan = new Scanner(line);
        while (line != null) {
            Employee emp = new Employee();
            scan.useDelimiter(",");

            while (scan.hasNext()) {
                emp.setEmployeeID(Integer.parseInt(scan.next()));
                emp.setFirstName(scan.next());
                emp.setLastName(scan.next());
                emp.setSalary(Double.parseDouble(scan.next()));
                line = reader.readLine();
            }
            tree.insert(emp);
        }
    }catch (IOException e) {
        e.printStackTrace();
    } finally {
        reader.close();
        scan.close();
    }
}

答案3

得分: 0

你不需要同时使用BufferedReaderScanner。一个Scanner就足够了:

public static BST readFile(File file) throws FileNotFoundException {
    try (Scanner scan = new Scanner(file)) {
        scan.useLocale(Locale.US);  // 读取双精度值必须使用
        
        BST bst = new BST();
        
        while (scan.hasNext()) {
            Employee employee = new Employee();
            employee.setEmployeeID(scan.nextInt());
            employee.setFirstName(scan.next());
            employee.setLastName(scan.next());
            employee.setSalary(scan.nextDouble());
            bst.insert(employee);
        }
        
        bst.inOrder();
        return bst;
    }
}
英文:

You do not need to use both BufferedReader and Scanner. One Scanner is enough:

public static BST readFile(File file) throws FileNotFoundException {
    try (Scanner scan = new Scanner(file)) {
        scan.useLocale(Locale.US);  // mandatory for read double values

        BST bst = new BST();

        while (scan.hasNext()) {
            Employee employee = new Employee();
            employee.setEmployeeID(scan.nextInt());
            employee.setFirstName(scan.next());
            employee.setLastName(scan.next());
            employee.setSalary(scan.nextDouble());
            bst.insert(employee);
        }

        bst.inOrder();
        return bst;
    }
}

huangapple
  • 本文由 发表于 2020年8月22日 03:02:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63528701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定