Java 在文件中写入对象的 ArrayList

Java write ArrayList of Objects in a File

我想将存储在密码数据库中的所有密码对象写入文件中。但是在这个文件中有许多神秘的标志。我希望我的 Arraylist 在文件中像这样打印:MyPC 超级密码等。

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();
    }
 }

}

ObjectOutputStream 仅在您想要 Java 易于阅读且不一定易于人类阅读的序列化格式时使用。

如果您想要特定的格式,您可能会受益于使用 PrintStream