Domanda

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

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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 { } 

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

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 {
....

Make this class Serializeable

class SeznamLodi implements java.io.Serializeable

If SeznamLodi is your own, make it Serializable by

  public class SeznamLodi implements Serializable {

  }

Read about Serialization#Java.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top