我想将已创建的对象写入文本文件Members.txt
,但似乎无法写入,也没有例外。 Object类实现Serializable。
我尝试将对象添加到Arraylist
,然后将Arraylist
写入文件,并且还尝试直接写入对象。
Client client = new Client(name, age, email, phoneNum);
//test object
System.out.print(client.toString());
/*write new obj to txt file*/
String filename = "Members.txt";
File file = new File(filename);
List < Client > obj;
obj = new ArrayList < Client > ();
obj.add(new Client(name, age, email, phoneNum));
obj.add(new Client(name, age, email, phoneNum));
try {
//INCLUDES BOTH attempts
//Attempt 1(Direct writing)
boolean openToAppend = true;
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file, openToAppend));
out.writeObject(client);
out.close();
//Attempt 2 (using arraylist)
FileOutputStream fileOut = new FileOutputStream("Members.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.println("Print Successful");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}