Классы ObjectOutputStream и ObjectInputStream служат для сохранения в потоке и чтения из потока объектов, то есть для сериализации и десериализации объектов. Пример:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javainputoutput;
/** * * @author martyshov */ import java.io.*; import java.nio.*; import java.util.*;
public class JavaInputOutput {
/** * @param args the command line arguments */ public static void main(String[] args) throws IOException {
String fileName = "C:/object.obj";
class MyTestClass implements Serializable {
int i; String s; float f;
public MyTestClass(int i, String s, float f) { this.i = i; this.f = f; this.s = s; }
@Override public String toString() { return "MyTestClass{" + "i=" + i + ", s=" + s + ", f=" + f + '}'; }
}
try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));) {
os.writeObject(new MyTestClass(1, "Это первый объект", 0.1f)); os.writeObject(new MyTestClass(2, "Это второй объект", 0.2f)); os.writeObject(new MyTestClass(3, "Это третий объект", 0.3f));
} catch (IOException e) { System.err.println(e.fillInStackTrace()); }
try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileName))) {
System.out.println(is.readObject()); System.out.println(is.readObject()); System.out.println(is.readObject());
} catch (IOException e) { System.err.println(e.fillInStackTrace()); } catch(ClassNotFoundException n){ System.err.println(n.fillInStackTrace()); }
} }
|