[英]Java write ArrayList of Objects in a File
我想编写所有密码对象,这些对象存储在PasswordDatabase中的文件中。 但是在这个文件中有许多神秘的迹象。 我希望我的Arraylist在文件中打印如下:MyPC superpassword,依此类推。
public class PasswordDatabase {
ArrayList<Password> password = new ArrayList<Password>();
public void getAllPasswords() {
for (Password p : password) {
System.out.println(p.getPassword() + " " + p.getLocation());
}
}
}
public class Password implements Serializable {
String Password;
String Location;
public Password(String Password, String Location) {
this.Password = Password;
this.Location = Location;
}
}
class Test {
PasswordDataBase db = new PasswordDatabase
public void writeInFile() {
try {
FileOutputStream fos = new
FileOutputStream((System.getProperty("user.home")+"/test.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(db.getallPasswords());
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
仅当您想要一种易于Java读取且不一定易于人类读取的序列化格式时,才使用ObjectOutputStream
。
如果您想要特定的格式,则可能会改用PrintStream
受益。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.