2 回答

TA貢獻1786條經(jīng)驗 獲得超11個贊
由于您需要Person對象的輸出,因此我們需要重寫toString()類Person。
[威利·旺卡(WonkaWilly)、查理·巴克特(BucketCharlie)、喬爺爺(JoeGrandpa)]
class Person {
//Respective Constructor, Getter & Setter methods
/* Returns the string representation of Person Class.
* The format of string is firstName lastName (lastNameFirstName)*/
@Override
public String toString() {
return String.format(firstName + " " + lastName + "("+ lastName + firstName + ")");
}
}
有許多方法可以將對象寫入文件。這是與PrintWriter
將對象保存到文件
public static void save(String filename, List<Person> list) throws IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Person person : list) {
pw.println(person.toString());
}
pw.close();
}
或者使用序列化
// 你可以使用序列化機制。要使用它,您需要執(zhí)行以下操作:
將Person類聲明為實現(xiàn)Serializable:
public class Person implements Serializable {
...
@Override
public String toString() {
return String.format(firstName + " " + lastName + "("+ lastName + firstName + ")");
}
}
將您的列表寫入文件:
public static void save(String filename, List<Person> list) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
}
從文件中讀取列表:
public static List<Person> load(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
List<Person> list = (List<Person>) ois.readObject();
ois.close();
return list;
}

TA貢獻1827條經(jīng)驗 獲得超8個贊
你可以嘗試這樣的事情:
public static void save(String filename , ArrayList<Person> persons) throws IOException{
try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream (filename)))) {
for(int i = 0; i < persons.size; i++){
out.writeObject(persons.get(i));
}
}
}
添加回答
舉報