Java:导入包含空字段的csv会给出NullPointerException



我一直试图通过选择文件选择到我的数据库中的csv文件(包含空字段)。使用filechooser很重要,因为它是一个由学校使用的程序,他们希望能够通过导入他们拥有的excel/csv文件来导入他们每年的新学生记录。每当我运行下面给出的代码时,我都会得到以下错误:

SEVERE: null
java.lang.NullPointerException
at gui.FXMLStudentController$1.run(FXMLStudentController.java:86)
at java.lang.Thread.run(Thread.java:745)

我认为问题很明显。我如何使它工作而不出现错误?

进口国类:

public class ImportStudents
{
private File file;
private List<Student> students = new ArrayList<>();
public ImportStudents(File file) throws IOException 
{
    this.file = file;
}
public List importStudents() throws FileNotFoundException, IOException
{
   try(CSVReader reader = new CSVReader(new FileReader(file), ';'))
   {
   String[] nextLine;
   boolean notFirst = false;
   while ((nextLine = reader.readNext()) != null) {
        if (notFirst) {
             students.add(new Student(nextLine[3], nextLine[1], nextLine[0],nextLine[2]));
        }
        notFirst = true;
    }
   }catch(Exception e)
           {
               e.printStackTrace();
           }
    return students;
}
}

GUI中按下import按钮时的代码:

   @FXML
private void importeer(ActionEvent event)
{
    Stage stage = new Stage();
    ImportStudents = importStudents; //importStudents created earlier in the class
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open File");
    try
    {
        importStudents = new ImportStudents(fileChooser.showOpenDialog(stage));
        new Thread(new Runnable() {
            @Override
            public void run() 
            {
                try
                {
                    repository.importStudents(importStudents.importeerLeerlingen());
                }
                catch(Exception e)
                {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        }).start();
    }
    catch(Exception e)
    {
    }
}

仓库中的代码:

  public void importStudents(List<Student> students)
{
    try{
        em.getTransaction().begin();
        for (Student : students) 
        {
           em.persist(student);
        }
        em.getTransaction().commit();
    }
    finally
    {
        em.close();
    }
}

示例从csv文件我尝试导入这种方式:正如你所看到的,大多数时候电子邮件是空的(这是幼儿园的),但有些是给定的。

 SurName;Name;E-mail;Class
 Agacseven;Tuana;;3KA
 Ahmedov;Arman;;2KC
 Akcan;Efe;;3KA
 Akcan;Hanzade;;2KC
 Akhtar;Hussain;;1KA

学生构造函数是这样的

public Student(String class, String name, String surNaam, String email) 
{
    this.class = class;
    this.name = name;
    this.surNaam = surNaam;
    this.email = email;
}

Student构造函数是什么样子的?如果分隔符之间没有任何内容,我很难在javadocs中找到有值的readNext()在字符串引用中放入的内容。它可以是一个空字符串或null(看起来就是)。在这种情况下,你在Student构造函数中对该值所做的操作可能对空值是不合法的。

编辑

如果是这种情况,你可以在构造函数中处理null值的传递,或者编写一个静态方法,类似于:

public static String Convert(String str) {
    return str == null ? "" : str;
}

和实例化学生时:

new Student(Convert(nextLine[3]), ... );

相关内容

最新更新