【问题标题】:Use writer/reader for multiple fields对多个字段使用写入器/读取器
【发布时间】:2018-06-08 13:33:26
【问题描述】:

以下是我的 Student 对象的构造函数。我将使用学生名单。我需要存储列表,因此即使程序关闭,我仍然可以访问所有内容。我能想到的唯一方法是使用读取器/写入器和文本文件。

1) 有没有更有效的方法来存储这些信息?
2)如果没有,我如何使用读取器/写入器来存储每个字段?

public Student(String firstName, String lastName, String gender, String 
state, String school, String lit, String wakeUp, String sleep, String 
social,String contactInfo, String country, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.state = state;
this.school = school;
this.lit = lit;
this.wakeUp = wakeUp;
this.sleep = sleep;
this.social = social;
this.contactInfo = contactInfo;
this.country = country;
this.major = major;
}

【问题讨论】:

    标签: list text-files writer reader


    【解决方案1】:

    可能性确实是项目特定和主观的。 一些可能性包括:

    • CSV 文件,便于导出到其他程序和解析数据
    • 允许从任何具有 程序和互联网连接
    • 适用于不需要很多本地设备的文本文件 补充

    这实际上只取决于您希望如何实现它以及哪种方法最适合您的需求。

    要使用读取器/写入器来存储字段,您可以使用每个变量的访问器方法将它们逐行存储在文本文件中。下面是一些示例代码,可帮助您开始写入文件:

        PrintWriter outputStream = null;
    
        try {
            outputStream = new PrintWriter(new FileOutputStream(FILE_LOCATION));
        }
        catch (FileNotFoundException ex) {
            JOptionPane optionPane = new JOptionPane("Unable to write to file\n " + FILE_LOCATION, JOptionPane.ERROR_MESSAGE);
            JDialog dialog = optionPane.createDialog("Error!");
            dialog.setAlwaysOnTop(true);
            dialog.setVisible(true);
            System.exit(0);
        }
    
        Iterator<YOUR_OBJECT> i = this.List.iterator();
        YOUR_OBJECT temp = null;
        while (i.hasNext()) {
            temp = i.next();
            if (temp instanceof YOUR_OBJECT) {
                outputStream.println(temp.getAttribute());
            }
        }
        outputStream.close();
    

    【讨论】:

      猜你喜欢
      • 2022-08-23
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 2018-03-12
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多