Jan Hakl
Jan Hakl

Reputation: 75

Reading/writing object from file

Hello can anybody help me with writing and reading object in file in Java?

This is the code I use, it makes me this Exception: java.io.NotSerializableException Here is the code I use:

public void zapisDat() {
    sez = new SeznamLodi(seznamLodiPC, seznamLodiUser, seznamLodiZasahuHrac, seznamLodiZasahuPC);
    try {
        ObjectOutput out = new ObjectOutputStream(
                new FileOutputStream("mujseznam.dat"));
        out.writeObject(sez);
        out.close();             // a je to. Jednoduché, že?
    } catch (IOException e) {
        System.out.println("Chyba při zápisu souboru : " + e);
    }
}

public void nacteniDat() {
    try {
        // Načtení ze souboru
        File file = new File("mujseznam.dat");
        try (ObjectInputStream in = new ObjectInputStream(
                new FileInputStream(file))) {
            sez = (SeznamLodi) in.readObject();
        }
    } catch (ClassNotFoundException e) {
        System.out.println("Nemohu najít definici třídy: " + e);
    } catch (IOException e) {
        System.out.println("Chyba při čtení souboru : " + e);
    }
}

Thaks for any help

Upvotes: 0

Views: 94

Answers (6)

user2885596
user2885596

Reputation: 69

To make your object Serializable then you must have to implement the Serializable interface so that to instruct JVM to serialize the object of your own class which implements Serializable interface.

You code must implement Serializable interface look like,

public class < class_name > implements Serializable { } 

Upvotes: 1

vels4j
vels4j

Reputation: 11298

If SeznamLodi is your own, make it Serializable by

  public class SeznamLodi implements Serializable {

  }

Read about Serialization#Java.

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208964

Make this class Serializeable

class SeznamLodi implements java.io.Serializeable

Upvotes: 0

Arun
Arun

Reputation: 645

The object should be implementing the Serializable interface to be written to file. Specifically implement java.io.serializable.

import java.io.serializable

class SerializationBox implements Serializable {
....

Upvotes: 0

Dark Knight
Dark Knight

Reputation: 8337

As error say's, class (for object sez) does not implement Serializable interface. You can refer java papers to know how it works.

Upvotes: 0

rolfl
rolfl

Reputation: 17707

In order to write an Object to the ObjectOututStream it has to correctly support serialization.

Read the serialization tutorial and make your class SeznamLodi conform to the requirements.

Upvotes: 0

Related Questions