Exception in thread “main” java.lang.IllegalStateException: Scanner closed on File I/O

前端 未结 1 1756
旧巷少年郎
旧巷少年郎 2021-01-28 09:26

I\'m currently making a class that allows users to edit the line based on the ID that the user enters. However, I\'m having the error below:

Exception in thr

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 09:48

    The Scanner initialized over System.in to read the user input is fine. The IllegalStateException is thrown from the scanner initialized within the try block.

    The exception is thrown as you are closing the Scanner within the while loop. To avoid it move the x.close() and pw.close() statements to the finally block as below,

    PrintWriter pw = null;
    try {
        FileWriter fw = new FileWriter(tempfile,true);
        BufferedWriter bw = new BufferedWriter(fw);
        pw = new PrintWriter(bw);
        x = new Scanner(new File(filepath));
        x.useDelimiter("[,\n]");
    
        while (x.hasNext()){
            ...
            pw.flush();
        }
    
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error Occured");
    } finally {
        x.close();
        if (pw != null) {
            pw.close();
        }  
    }
    

    0 讨论(0)
提交回复
热议问题