将writer / reader用于多个字段

问题描述 投票:0回答:1

以下是我的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个回答
0
投票

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

  • 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();
© www.soinside.com 2019 - 2024. All rights reserved.