Java Tutorial/File/ObjectInputStream

Материал из Java эксперт
Перейти к: навигация, поиск

Create ObjectInputStream from FileInputStream

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;
public class ObjectReader {
  public static void main(String[] arguments) {
    try {
      FileInputStream fi = new FileInputStream("message.obj");
      ObjectInputStream oi = new ObjectInputStream(fi);
      Message mess = (Message) oi.readObject();
      System.out.println("Message:\n");
      System.out.println("From: " + mess.from);
      System.out.println("To: " + mess.to);
      System.out.println("Date: " + mess.when + "\n");
      for (int i = 0; i < mess.lineCount; i++)
        System.out.println(mess.text[i]);
      oi.close();
    } catch (Exception 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;
  }
}





Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class MyClass implements Serializable {
  String str;
  double[] vals;
  File fn;
  public MyClass(String s, double[] nums, String fname) {
    str = s;
    vals = nums;
    fn = new File(fname);
  }
  public String toString() {
    String data = "  str: " + str + "\n  vals: ";
    for (double d : vals)
      data += d + " ";
    data += "\n  fn: " + fn.getName();
    return data;
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    double v[] = { 1.1, 2.2, 3.3 };
    double v2[] = { 9.0, 8.0, 7.7 };
    MyClass obj1 = new MyClass("This is a test", v, "Test.txt");
    MyClass obj2 = new MyClass("Alpha Beta Gamma", v2, "Sample.dat");
    ObjectOutputStream fout = new ObjectOutputStream(new FileOutputStream("obj.dat"));
    System.out.println("obj1:\n" + obj1);
    fout.writeObject(obj1);
    System.out.println("obj2:\n" + obj2);
    fout.writeObject(obj2);
    fout.close();
    ObjectInputStream fin = new ObjectInputStream(new FileInputStream("obj.dat"));
    MyClass inputObj;
    inputObj = (MyClass) fin.readObject();
    System.out.println("First object:\n" + inputObj);
    inputObj = (MyClass) fin.readObject();
    System.out.println("Second object:\n" + inputObj);
    fin.close();
  }
}





Reading objects from file using ObjectInputStream

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class Main {
  public static void main(String[] args) throws Exception {
    ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("yourFile.dat"));
    Object obj = null;
    while ((obj = inputStream.readObject()) != null) {
      if (obj instanceof Person) {
        System.out.println(((Person) obj).toString());
      }
    }
    inputStream.close();
  }
}
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();
  }
}





Store objects in file

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Main {
  public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("books.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    Book book = new Book("1", "Java", "A");
    oos.writeObject(book);
    oos.flush();
    oos.close();
    FileInputStream fis = new FileInputStream("books.dat");
    ObjectInputStream ois = new ObjectInputStream(fis);
    book = (Book) ois.readObject();
    System.out.println(book.toString());
    ois.close();
  }
}
class Book implements Serializable {
  private String isbn;
  private String title;
  private String author;
  public Book(String isbn, String title, String author) {
    this.isbn = isbn;
    this.title = title;
    this.author = author;
  }
  public String toString() {
    return "[Book: " + isbn + ", " + title + ", " + author + "]";
  }
}