1

I tried to use ObjectInputStream to write an Object in a file but when i read the file with ObjectInputStream and return in into another object from the same class the results are different and when i print out the second object in console it shows me the class name plus some nonsense numbers Whats wrong?!

import java.io.Serializable;

public class Users implements Serializable {
    private static final long serialVersionUID = 1L;
    private String username;
    private String password;

    public Users(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        File file = new File("userinfo.txt");
        if (!file.exists()) {
            file.createNewFile();
        }

        Users user1 = new Users("Omid","1234");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

        objectOutputStream.writeObject(user1);
        objectOutputStream.close();

        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        Users user2 = (Users)objectInputStream.readObject();
        objectInputStream.close();

        System.out.println(user2);

    }
}

and this is what console shows

Users@378bf509
Omid
  • 301
  • 1
  • 2
  • 12
  • Your `Users` class doesn't override `toString()` which might not want to print the password for example. You can use your IDE to generate a `toString()` for you. – Peter Lawrey Jul 08 '18 at 18:25
  • You don't need to create a file to write to it. If the file doesn't exist it gets created anyway. – Peter Lawrey Jul 08 '18 at 18:26

0 Answers0