Search code examples
javastringfileioprintwriter

Java write ArrayList of Objects in a File


i want to write all Password Objects, which are stored in PasswordDatabase in a file. But in this file a are many cryptic signs. I want my Arraylist print like this in the file: MyPC superpassword and so on.

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

}


Solution

  • The ObjectOutputStream is only meant to be use if you want a serialization format that is easy to read by Java, and not necessarily easy to read by humans.

    If you want a particular format, you would probably benefit from using a PrintStream instead.