在Java中使用while循环进行Try-Catch

时间:2015-03-18 02:33:05

标签: java file-io while-loop try-catch

所以基本上我的代码试图读取.txt文件,然后用这些变量(long,string,string,double,double)创建对象。当.txt文件中的变量ISN为长或字符串或双精度时,它将被写入另一个文件。我已经写了这个代码,但它没有超过第一个catch (InputMismatchException n)。我的代码出了什么问题?

int i = 0;
ArrayList<Employee> ArrEmployee = new ArrayList<Employee>(); //  array for employee objects

try {
    Scanner txtIn = new Scanner(new File("payroll.txt"));


    while (txtIn.hasNext()) { // looping through the payroll.txt file and creating Employee objects from its data
        try {
            long EmployeeNumber = txtIn.nextLong();
            String EmployeeName = txtIn.next();
            String LastName = txtIn.next();
            double HoursWorked = txtIn.nextDouble();
            double HourlyWage = txtIn.nextDouble();
            if (HourlyWage > 10.35){ 
                throw new InputMismatchException(); // throws exception if the hourly wage is less than 10.35$
            }
            else
                ArrEmployee.add(new Employee(EmployeeNumber,EmployeeName,LastName,HoursWorked,HourlyWage)); // creates Employee objects according to the input payroll.txt
            i++;
        } catch (InputMismatchException n) { // catching long,strings and doubles in the payroll.txt that aren't valid
            PrintWriter txtOut = new PrintWriter("payrollError.txt");
            txtOut.println(Employee.EmployeeNumber + " " + Employee.EmployeeName + " " + Employee.LastName + " " + Employee.HoursWorked + " " + Employee.HourlyWage);
            txtOut.close();
        }
    }
} catch (FileNotFoundException e) {
    System.out.println("File payroll.txt was not found.");
}

路径文件没问题。为了便于理解,我缩短了它。

1 个答案:

答案 0 :(得分:1)

您为PrintWriter使用的构造函数实际上会覆盖该文件(如果该文件已存在)。来自documentation

  

fileName - 用作此编写者目标的文件的名称。 如果该文件存在,那么它将被截断为零大小;否则,将创建一个新文件。输出将被写入文件并被缓冲。

你应该在循环之前创建一次txtOut并在循环之后关闭它。通过这种方式,它只会被打开一次,而不是从头开始捕获每个异常。