提问人:Avi 提问时间:1/29/2023 更新时间:1/29/2023 访问量:45
从文件中读取对象并将它们输出到一行中,输出到另一个文件
Read objects from a file and output them into a single line into another file
问:
目前,我有一个对象数组,我将其写入 .ser 文件。现在我想做的是让个人只出现在另一个文件中一次,并将他们的所有数字加起来。到目前为止,我用函数中的更新编号编写了每一行,但不确定如何让它们只出现一次,所有数字加起来。
这是我的代码:
公共类 IOStream {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException {
Person[] people = new Person[14];
people[0] = new Professor("Professor", "Issac", "Newton", "Physcis", 6);
people[1] = new TA("TA", "Marie", "Curie", "Physics", 6);
people[2] = new Professor("Professor", "Issac", "Newton", "Calculus", 4);
people[3] = new Student("Student", "Amy", "Adams", "Calculus", 4);
people[4] = new Student("Student", "Will", "Smith", "Calculus", 4);
people[5] = new Student("Student", "Brad", "Pitt", "Physics", 6);
people[6] = new Student("Student", "Will", "Smith", "Physics", 6);
people[7] = new Professor("Professor", "Dimitri", "Mendeleev", "Chemistry", 6);
people[8] = new TA("TA", "Carl", "Gauss", "Calculus", 4);
people[9] = new Student("Student", "Amy", "Adams", "Economics", 3);
people[10] = new Professor("Professor", "Adam", "Smith", "Economics", 3);
people[11] = new TA("TA", "Marie", "Curie", "Chemistry", 6);
people[12] = new Student("Student", "Brad", "Pitt", "Chemistry", 6);
people[13] = new Student("Student", "Will", "Smith", "Chemistry", 6);
//WRITING
try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("object.ser"))) {
for (int i = 0; i < people.length; i++) {
out.writeObject(people[i]);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
//READING INPUT
try ( ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.ser"))) {
ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream("output.ser"));
Person lol;
Person [] list;
int i;
while ((lol = (Person) in.readObject()) != null) {
writer.writeObject(lol.title + " " + lol.fName + " " + lol.lName + " " + lol.getParticipatingHours(lol.courseHours));
}
} catch (EOFException i) {
//System.out.println("lol");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error");
}
try {
ObjectInputStream reader = new ObjectInputStream(new FileInputStream("output.ser"));
Object line;
while ((line = reader.readObject()) != null) {
System.out.println(line);
}
} catch (EOFException i) {
//System.out.println("lol");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是我从输出文件中读取的输出: 跑: 伊萨克·牛顿教授 4 TA 居里夫人 2 伊萨克·牛顿教授 3 学生 艾米·亚当斯 4 学生威尔·史密斯 4 学生布拉德·皮特(Brad Pitt) 6 学生威尔·史密斯 6 迪米特里·门捷列夫教授 4 TA 卡尔·高斯 1 学生艾米·亚当斯(Amy Adams) 3 亚当·斯密教授 2 TA 居里夫人 2 学生布拉德·皮特(Brad Pitt) 6 学生威尔·史密斯 6
答: 暂无答案
评论