Java编写文件中对象的ArrayList

时间:2018-04-08 21:42:16

标签: java string file io printwriter

我想将所有密码对象写入文件中,密码对象存储在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();
    }
 }

}

1 个答案:

答案 0 :(得分:0)

如果您想要一种易于Java阅读的序列化格式,并且不一定容易被人阅读,那么ObjectOutputStream只能用于。

如果您需要特定格式,则可能会因使用PrintStream而受益。

相关问题