【发布时间】:2015-08-29 17:20:37
【问题描述】:
我一直在尝试通过将带有文件选择器的文件选择到我的数据库中来导入 csv 文件(包含空字段)。使用文件选择器很重要,因为它是一个供学校使用的程序,他们希望能够通过导入他们拥有的 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 代码:
@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;
}
【问题讨论】:
-
堆栈跟踪?例外?线扔在哪里?
标签: java csv import field filechooser