Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
418 views

So I'm having trouble with my coding. When I use readObject in my code, I receive an IOException. The application runs normally, but when I try to use readObject, I get an exception; here is the code I use to save objects:

[code]

File f = new File("employees.obj");
    ObjectOutputStream objOut = null;

    try {

        objOut = new ObjectOutputStream(new BufferedOutputStream(
                new FileOutputStream(f)));
        objOut.writeObject(newEmployee);
        objOut.flush();

        System.out.println("Object is serialized.");

    } catch (FileNotFoundException e) {
        System.out.println("File not found!");

    } catch (IOException e) {
        System.out.println("Failed!");

    } finally {

        if (objOut != null) {
            try {

                objOut.close();
            } catch (IOException e) {
            }
        }
    }[/code]

and here is the code I use to restore objects:

[code]

File f = new File("employees.obj");
    ObjectInputStream objIn = null;
    ArrayList<Employee> c = new ArrayList<Employee>();
    try {
        objIn = new ObjectInputStream(new BufferedInputStream(
                new FileInputStream(f)));
        while (objIn.readObject() != null) {
            Person employee = (Person) objIn.readObject();
            System.out.println("hello");
            System.out.println(employee.toString());
        }
        System.out.println(c.toString());
        return c;

    } catch (FileNotFoundException e) {
        System.out.println("1");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        System.out.println("3");
    } catch (ClassCastException e) {
        System.out.println("4");
    } finally {

        if (objIn != null) {
            try {
                objIn.close();
            } catch (IOException e) {
                System.out.println("4");
            }
        }
    }
    return c;[/code]

and the result in console:

[code]

at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2553)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1296)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at org.bihe.DeSerializer.deSerializeEmployees(DeSerializer.java:20)
at org.bihe.Main.enterAsManager(Main.java:238)
at org.bihe.Main.menu(Main.java:92)
at org.bihe.Main.main(Main.java:50)[/code]

 

in Algorithms and Problems by Expert (650 points) | 418 views

Please log in or register to answer this question.

Get best answers to any doubt/query/question related to programming , jobs, gate, internships and tech-companies. Feel free to ask a question and you will receive the best advice/suggestion related to anything you ask about software-engineering , development and programming problems .