Java Array将输入保存到txt文件

时间:2014-11-30 19:58:17

标签: java file arraylist

我已创建此代码以将学生信息保存到txt文件,但它只保存名称。我发现这个想法有什么不对吗?我没有得到任何错误programma运行很好,期待一些错误处理和我必须添加的其他东西。

主要课程

public class Main {

    public static void main(String[] args) throws IOException {
        File fileName = new File("Students.txt");
        ArrayList Students = new ArrayList();
        String studentName = " ";
        String studentSName = " ";
        String idstudent = " ";
        String course = " ";
        while (!studentName.isEmpty()) {
            studentName = JOptionPane.showInputDialog("Student's Name: ");
            studentSName = JOptionPane.showInputDialog("Student's Surname: ");
            idstudent = JOptionPane.showInputDialog("Student's IDnumber: ");
            course = JOptionPane.showInputDialog("Student's Course: ");
            if (!studentName.isEmpty()) {
                Students.add(studentName);
            }
        }
        try {
            FileWriter fw = new FileWriter(fileName);
            Writer output = new BufferedWriter(fw);
            int sz = Students.size();
            for (int i = 0; i < sz; i++) {
                output.write(Students.get(i).toString() + "\n");
            }
            output.close();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "file not found");
        }
    }
}

第二课:

public class filereading {

    public static void main(String[] args) {
        String FileName = "students.txt";
        String line;
        ArrayList Students = new ArrayList();

        try {
            BufferedReader input = new BufferedReader(new FileReader(FileName));
            if (!input.ready()) {
                throw new IOException();
            }
            while ((line = input.readLine()) != null) {
                Students.add(line);
            }
            input.close();
        } catch (IOException e) {
            System.out.println(e);
        }
        int sz = Students.size();
        for (int i = 0; i < sz; i++) {
            System.out.println(Students.get(i).toString());

        }
    }
}

2 个答案:

答案 0 :(得分:3)

因为您只向List添加名称

 if (!studentName.isEmpty()) Students.add(studentName);

答案 1 :(得分:1)

您必须添加以下内容:

Students.add(String.format("%s %s, id: %s, course: %s", studentName, studentSName, idstudent, course));