Exception in thread “main” java.lang.IllegalStateException: 文件 I/O 中的扫描器已关闭

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

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

问题

我目前正在制作一个类允许用户根据用户输入的ID编辑行但是我遇到了以下错误

>异常线程"main" java.lang.IllegalStateException: Scanner已关闭"

即使我在```int phone input```下面放了```scanner.close()```。
是否有任何解释为什么会发生这种情况

    package com.company;
    
    import javax.sound.midi.SysexMessage;
    import java.io.*;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Scanner;
    
    public class Edit {
        static Scanner x;
    
        public static void editRecord() throws ParseException {
            Scanner scanner = new Scanner(System.in);
            System.out.println("输入您的ID");
            String ID = scanner.nextLine();
            System.out.println("输入您的新姓名");
            String name = scanner.nextLine();
            System.out.println("输入您的新电子邮件");
            String email = scanner.nextLine();
            System.out.println("输入您的新地址");
            String address = scanner.nextLine();
            System.out.println("输入您的新日期");
            String date = scanner.nextLine();
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            Date userDate = format.parse(date);
            System.out.println("输入您的性别");
            String gender = scanner.nextLine();
            boolean Gender = Boolean.parseBoolean(gender);
            System.out.println("输入您的新电话号码");
            int phone = scanner.nextInt();
    
            String filepath = "leads.csv";
            String tempfile = "temp.csv";
            File oldFile = new File(filepath);
            File newFile = new File(tempfile);
            String ID1 = ""; String name1 = ""; String email1=""; String address1 = ""; String userdate1 = "";
            String Gender1 = ""; String phone1 = "";
            scanner.close();
            try{
                FileWriter fw = new FileWriter(tempfile,true);
                BufferedWriter bw = new BufferedWriter(fw);
                PrintWriter pw = new PrintWriter(bw);
                x = new Scanner(new File(filepath));
                x.useDelimiter("[,\n]");
    
                while (x.hasNext()){
                    ID1 = x.next();
                    name1 = x.next();
                    phone1 = x.next();
                    email1 = x.next();
                    address1 = x.next();
                    userdate1 = x.next();
                    Gender1 = x.next();
                    if(ID1.equals(ID)){
                        pw.println(name+","+phone+","+email+","+address+","+userDate+","+Gender);
                    }
                    else {
                        pw.println(name1+","+phone1+","+email1+","+address1+","+userdate1+","+Gender1);
                    }
                    x.close();
                    pw.flush();
                    pw.close();
                    oldFile.delete();
                    File dump = new File(filepath);
                    newFile.renameTo(dump);
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("发生错误");
            }
        }
    }
英文:

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 thread "main" java.lang.IllegalStateException: Scanner closed".

Even though I have put a scanner.close() below the int phone input.
Is there any explanation on why is this happening

package com.company;
import javax.sound.midi.SysexMessage;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Edit {
static Scanner x;
public static void editRecord() throws ParseException {
Scanner scanner = new Scanner(System.in);
System.out.println("ENter your ID");
String ID = scanner.nextLine();
System.out.println("ENter your new name");
String name = scanner.nextLine();
System.out.println("ENter your new EMail");
String email = scanner.nextLine();
System.out.println("ENter your new Address");
String address = scanner.nextLine();
System.out.println("ENter your new Date");
String date = scanner.nextLine();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Date userDate = format.parse(date);
System.out.println("ENter your Gender");
String gender = scanner.nextLine();
boolean Gender = Boolean.parseBoolean(gender);
System.out.println("ENter your new phone number");
int phone = scanner.nextInt();
String filepath = "leads.csv";
String tempfile = "temp.csv";
File oldFile = new File(filepath);
File newFile = new File(tempfile);
String ID1 = ""; String name1 = "";String email1="";String address1 = ""; String userdate1 = "";
String Gender1 = ""; String phone1 = "";
scanner.close();
try{
FileWriter fw = new FileWriter(tempfile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\n]");
while (x.hasNext()){
ID1 = x.next();
name1 = x.next();
phone1 = x.next();
email1 = x.next();
address1 = x.next();
userdate1 = x.next();
Gender1 = x.next();
if(ID1.equals(ID)){
pw.println(name+","+phone+","+email+","+address+","+userDate+","+Gender);
}
else {
pw.println(name1+","+phone1+","+email1+","+address1+","+userdate1+","+Gender1);
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error Occured");
}
}
}

答案1

得分: 1

初始化在 **System.in** 上的 **Scanner** 用于读取用户输入是没问题的。
**IllegalStateException** 异常是从在 **try 块** 内初始化的扫描器中抛出的。
异常被抛出是因为你正在 while 循环内关闭了 Scanner。
为了避免这个问题,将 **x.close()** 和 **pw.close()** 语句移到 **finally 块** 中,如下所示:
```java
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("发生错误");
} finally {
x.close();
if (pw != null) {
pw.close();
}  
}

<details>
<summary>英文:</summary>
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();
}
}


</details>

huangapple
  • 本文由 发表于 2020年9月13日 17:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63868968.html
匿名

发表评论

匿名网友

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

确定