Java Tutorial/File/ObjectOutputStream

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create a serialized output file.

import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class MainClass {
  // Throw exceptions to console:
  public static void main(String[] args) throws Exception {
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("X.file"));
    MyClass zorcon = new MyClass();
    out.writeObject(zorcon);
  }
}
// A serializable class.
class MyClass implements Serializable {
}





Create ObjectOutputStream out of FileOutputStream

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
public class ObjectWriter {
  public static void main(String[] arguments) {
    Message mess = new Message();
    String author = "London";
    String recipient = "G, B";
    String[] letter = { "Merry Christmas." };
    Date now = new Date();
    mess.writeMessage(author, recipient, now, letter);
    try {
      FileOutputStream fo = new FileOutputStream("Message.obj");
      ObjectOutputStream oo = new ObjectOutputStream(fo);
      oo.writeObject(mess);
      oo.close();
      System.out.println("Object created successfully.");
    } catch (IOException e) {
      System.out.println("Error - " + e.toString());
    }
  }
}
class Message implements Serializable {
  int lineCount;
  String from, to;
  Date when;
  String[] text;
  void writeMessage(String inFrom, String inTo, Date inWhen, String[] inText) {
    text = new String[inText.length];
    for (int i = 0; i < inText.length; i++)
      text[i] = inText[i];
    lineCount = inText.length;
    to = inTo;
    from = inFrom;
    when = inWhen;
  }
}





illustrates serialization and deserialization

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class shutdown {
  public static void main(String[] args) throws ClassNotFoundException, IOException {
    FileOutputStream fos = new FileOutputStream("objects.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject("asdf");
    oos.flush();
    fos.close();
    
    FileInputStream fis = new FileInputStream ("objects.tmp");  
    ObjectInputStream ois = new ObjectInputStream (fis);  
    String t = (String) ois.readObject ();  
    fis.close ();   
    
  }
}





Object IO

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
public class ObjectIOApp {
  public static void main(String args[]) throws IOException, ClassNotFoundException {
    File file = new File("test.txt");
    FileOutputStream outFile = new FileOutputStream(file);
    ObjectOutputStream outStream = new ObjectOutputStream(outFile);
    TestClass1 t1 = new TestClass1(true, 9, "A", 0.0001, "java");
    TestClass2 t2 = new TestClass2();
    String t3 = "This is a test.";
    Date t4 = new Date();
    outStream.writeObject(t1);
    outStream.writeObject(t2);
    outStream.writeObject(t3);
    outStream.writeObject(t4);
    outStream.close();
    outFile.close();
    FileInputStream inFile = new FileInputStream(file);
    ObjectInputStream inStream = new ObjectInputStream(inFile);
    System.out.println(inStream.readObject());
    System.out.println(inStream.readObject());
    System.out.println(inStream.readObject());
    System.out.println(inStream.readObject());
    inStream.close();
    inFile.close();
    file.delete();
  }
}
class TestClass1 implements Serializable {
  boolean b;
  int i;
  char c;
  double d;
  String s;
  TestClass1(boolean b, int i, char c, double d, String s) {
    this.b = b;
    this.i = i;
    this.c = c;
    this.d = d;
    this.s = s;
  }
  public String toString() {
    String r = String.valueOf(b) + " ";
    r += String.valueOf(i) + " ";
    r += String.valueOf(c) + " ";
    r += String.valueOf(d) + " ";
    r += String.valueOf(s);
    return r;
  }
}
class TestClass2 implements Serializable {
  int i;
  TestClass1 tc1;
  TestClass1 tc2;
  TestClass2() {
    i = 0;
    tc1 = new TestClass1(true, 2, "j", 1.234, "Java");
    tc2 = new TestClass1(false, 7, "J", 2.468, "JAVA");
  }
  public String toString() {
    String r = String.valueOf(i) + " ";
    r += tc1.toString() + " ";
    r += tc2.toString();
    return r;
  }
}





Reading Basic Data From an Object Stream

import java.awt.Polygon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class MainClass {
  public static void main(String[] args) {
    int[] x = new int[] { 1, 2, 3 };
    int[] y = new int[] { 4, 5, 6 };
    Polygon polygon = new Polygon(x, y, x.length);
    try {
      ObjectOutputStream objectOut = new ObjectOutputStream(new BufferedOutputStream(
          new FileOutputStream("C:/Polygons.bin")));
      objectOut.writeObject(polygon);
      objectOut.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
    try {
      ObjectInputStream objectIn = new ObjectInputStream(new BufferedInputStream(
          new FileInputStream("C:/Polygons.bin")));
      Polygon theLine = (Polygon) objectIn.readObject();
      System.out.println(theLine);
      objectIn.close();
    } catch (Exception e) {
      e.printStackTrace(System.err);
    }
  }
}





Serializing an Object (JButton)

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import javax.swing.JButton;
public class Main {
  public static void main(String[] argv) throws Exception {
    Object object = new JButton("push me");
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
    out.writeObject(object);
    out.close();
    // Serialize to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    out = new ObjectOutputStream(bos);
    out.writeObject(object);
    out.close();
    // Get the bytes of the serialized object
    byte[] buf = bos.toByteArray();
    System.out.println(new String(buf));
  }
}





Try to recover a serialized file without the class of object that"s stored in that file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class MainClass {
  public static void main(String[] args) throws Exception {
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("X.file"));
    MyClass zorcon = new MyClass();
    out.writeObject(zorcon);
    
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("X.file")));
      Object mystery = in.readObject();
      System.out.println(mystery.getClass());
    
  }
}
// A serializable class.
class MyClass implements Serializable {
}





Writing objects to file with ObjectOutputStream

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
  private String firstName;
  private String lastName;
  private int age;
  public Person() {
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String toString() {
    StringBuffer buffer = new StringBuffer();
    buffer.append(firstName);
    buffer.append("\n");
    buffer.append(lastName);
    buffer.append("\n");
    buffer.append(age);
    buffer.append("\n");
    return buffer.toString();
  }
}
public class Main {
  public static void main(String[] args) throws Exception {
    ObjectOutputStream outputStream = null;
    outputStream = new ObjectOutputStream(new FileOutputStream("yourFile.dat"));
    Person person = new Person();
    person.setFirstName("A");
    person.setLastName("B");
    person.setAge(38);
    outputStream.writeObject(person);
    person = new Person();
    person.setFirstName("C");
    person.setLastName("D");
    person.setAge(22);
    outputStream.writeObject(person);
  }
}