Serializace
Pes.java
package soubory;
import java.io.Serializable;
public class Pes implements Serializable{
String jmeno;
String majitel;
public Pes(String jmeno, String majitel){
this.jmeno = jmeno;
this.majitel = majitel;
}
@Override
public String toString(){
return jmeno+"("+majitel+")";
}
}
Main.java
package soubory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
try {
ObjectOutputStream file = new ObjectOutputStream(new FileOutputStream("psi.pes"));
Pes alik = new Pes("alik", "novak");
Pes azor = new Pes("azor", "dvorak");
file.writeInt(2);
file.writeObject(alik);
file.writeObject(azor);
file.close();
ObjectInputStream vstup = new ObjectInputStream(new FileInputStream("psi.pes"));
//ukladat pocet neni potreba, ale par veci se tim zjednodusi
int pocet = vstup.readInt();
for (int i =0; i<pocet; i++){
Object o = vstup.readObject();
if (o instanceof Pes){
System.out.println(((Pes)o).jmeno);
}
System.out.println(o.getClass().getName());
}
} catch (IOException ex) {
//neco se pokazilo
}
}
}
Back to top