I am learning Java and I'm trying to get a programme to write the attributes of one class instance of another into a .txt file, like a phonebook for instance. I have a class User :
package idpack;
import java.io.Serializable;
public class User implements Serializable {
private String id;
private String mdp;
public User (String id, String mdp) {
this.id = id;
this.mdp = mdp;
}
}
and a main, in which I declare my ObjectOutputStream, ObjectInputStream, my scanner and then try to write the input from the scanner into the file. It looks like this:
package idpack;
// import everything here
public class Main {
public static void main(String[] args) throws IOException {
ObjectInputStream ois;
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(
new File("identifiant.txt"))));
ois = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(
new File ("identifiant.txt"))));
ArrayList<User> ul = new ArrayList<User>();
Scanner scan = new Scanner(System.in);
boolean isTyping = true;
try {
while(isTyping) {
System.out.println("press['x' to exit]\n = type in the id :");
String id = scan.next();
if (id.equalsIgnoreCase("x")) {
break;
}
System.out.println("type in the number :");
String mdp = scan.next();
User u = new User(id, mdp);
ul.add(u);
oos.writeObject(new User (id, mdp));
}
for (User t:ul) {
System.out.println(((User)ois.readObject()).toString());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
oos.close();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (EOFException e) { // the console throws EOFException ObjectInputStream of all kinds, so I though catching them would be a good idea, but this code doesn't do anything to remedy it
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have tried moving around where I close oos and ois and getting rid of the first try catch block, but to no avail. The scanner in itself is working, I largely used this post as a model: Adding objects to an array list with scanner in Java