Java/File Input Output/ObjectInputStream

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

Create ObjectInputStream out of FileInputStream

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class CardReader {
  public static void main(String[] args) {
    Card3 card = null;
    try {
      FileInputStream in = new FileInputStream("card.out");
      ObjectInputStream ois = new ObjectInputStream(in);
      card = (Card3) (ois.readObject());
    } catch (Exception e) {
      System.out.println("Problem serializing: " + e);
    }
    System.out.println("Card read is: " + card);
  }
}
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *  - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *  - Neither the name of Sun Microsystems nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
class Card3 implements Serializable {
  private int suit = UNASSIGNED;
  private int number = UNASSIGNED;
  public final static int UNASSIGNED = -1;
  public final static int DIAMONDS = 1;
  public final static int CLUBS = 2;
  public final static int HEARTS = 3;
  public final static int SPADES = 4;
  public final static int ACE = 1;
  public final static int KING = 13;
  public Card3(int number, int suit) {
    if (isValidNumber(number)) {
      this.number = number;
    } else {
      // Error
    }
    if (isValidSuit(suit)) {
      this.suit = suit;
    } else {
      // Error
    }
  }
  public int getSuit() {
    return suit;
  }
  public int getNumber() {
    return number;
  }
  public static boolean isValidNumber(int number) {
    if (number >= ACE && number <= KING) {
      return true;
    } else {
      return false;
    }
  }
  public static boolean isValidSuit(int suit) {
    if (suit >= DIAMONDS && suit <= SPADES) {
      return true;
    } else {
      return false;
    }
  }
  public boolean equals(Object obj) {
    if (obj instanceof Card3) {
      Card3 card = (Card3) obj;
      if (card.getNumber() == this.number && card.getSuit() == this.suit) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  public int hashCode() {
    return number * suit;
  }
  public String toString() {
    return numberToString(this.number) + " of " + suitToString(this.suit);
  }
  public static String numberToString(int number) {
    String result = "";
    switch (number) {
    case ACE:
      result = "Ace";
      break;
    case 2:
      result = "Two";
      break;
    case 3:
      result = "Three";
      break;
    case 4:
      result = "Four";
      break;
    case 5:
      result = "Five";
      break;
    case 6:
      result = "Six";
      break;
    case 7:
      result = "Seven";
      break;
    case 8:
      result = "Eight";
      break;
    case 9:
      result = "Nine";
      break;
    case 10:
      result = "Ten";
      break;
    case 11:
      result = "Jack";
      break;
    case 12:
      result = "Queen";
      break;
    case KING:
      result = "King";
      break;
    case UNASSIGNED:
      result = "Invalid Number";
      break;
    }
    return result;
  }
  public static String suitToString(int suit) {
    String result = "";
    switch (suit) {
    case DIAMONDS:
      result = "Diamonds";
      break;
    case CLUBS:
      result = "Clubs";
      break;
    case HEARTS:
      result = "Hearts";
      break;
    case SPADES:
      result = "Spades";
      break;
    case UNASSIGNED:
      result = "Invalid Suit";
      break;
    }
    return result;
  }
}





new ObjectInputStream(new BufferedInputStream(new FileInputStream(StringFileName)));

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.Calendar;
public class ObjectStreams {
  static final String dataFile = "invoicedata";
  static final BigDecimal[] prices = { new BigDecimal("19.99"),
      new BigDecimal("9.99"), new BigDecimal("15.99"), new BigDecimal("3.99"),
      new BigDecimal("4.99") };
  static final int[] units = { 12, 8, 13, 29, 50 };
  static final String[] descs = { "Java T-shirt", "Java Mug",
      "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };
  public static void main(String[] args) throws IOException,
      ClassNotFoundException {
    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(new BufferedOutputStream(
          new FileOutputStream(dataFile)));
      out.writeObject(Calendar.getInstance());
      for (int i = 0; i < prices.length; i++) {
        out.writeObject(prices[i]);
        out.writeInt(units[i]);
        out.writeUTF(descs[i]);
      }
    } finally {
      out.close();
    }
    ObjectInputStream in = null;
    try {
      in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(
          dataFile)));
      Calendar date = null;
      BigDecimal price;
      int unit;
      String desc;
      BigDecimal total = new BigDecimal(0);
      date = (Calendar) in.readObject();
      System.out.format("On %tA, %<tB %<te, %<tY:%n", date);
      try {
        while (true) {
          price = (BigDecimal) in.readObject();
          unit = in.readInt();
          desc = in.readUTF();
          System.out.format("You ordered %d units of %s at $%.2f%n", unit,
              desc, price);
          total = total.add(price.multiply(new BigDecimal(unit)));
        }
      } catch (EOFException e) {
      }
      System.out.format("For a TOTAL of: $%.2f%n", total);
    } finally {
      in.close();
    }
  }
}





ObjectInputStream, ObjectOutputStream and java.io.Serializable

 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Engine implements Serializable {
  private int numCylinders;
  Engine(int numCylinders) {
    this.numCylinders = numCylinders;
  }
  int getNumCylinders() {
    return numCylinders;
  }
}
class Car implements Serializable {
  private int numTires;
  private Engine e;
  private String name;
  Car(String name, int numTires, Engine e) {
    this.name = name;
    this.numTires = numTires;
    this.e = e;
  }
  int getNumTires() {
    return numTires;
  }
  Engine getEngine() {
    return e;
  }
  String getName() {
    return name;
  }
}
class Main {
  public static void main(String[] args) throws Exception {
    Car c1 = new Car("Some car", 4, new Engine(6));
    ObjectOutputStream oos = null;
    FileOutputStream fos = new FileOutputStream("car.ser");
    oos = new ObjectOutputStream(fos);
    oos.writeObject(c1);
    ObjectInputStream ois = null;
    FileInputStream fis = new FileInputStream("car.ser");
    ois = new ObjectInputStream(fis);
    Car c2 = (Car) ois.readObject();
    System.out.println("Number of tires = " + c2.getNumTires());
    System.out.println("Number of cylinders = " + c2.getEngine().getNumCylinders());
    System.out.println("Name = " + c2.getName());
  }
}





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();
  }
}





Read different data types from ObjectInputStream

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.Calendar;
public class ObjectStreams {
  static final String dataFile = "invoicedata";
  static final BigDecimal[] prices = { new BigDecimal("19.99"),
      new BigDecimal("9.99"), new BigDecimal("15.99"), new BigDecimal("3.99"),
      new BigDecimal("4.99") };
  static final int[] units = { 12, 8, 13, 29, 50 };
  static final String[] descs = { "Java T-shirt", "Java Mug",
      "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };
  public static void main(String[] args) throws IOException,
      ClassNotFoundException {
    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(new BufferedOutputStream(
          new FileOutputStream(dataFile)));
      out.writeObject(Calendar.getInstance());
      for (int i = 0; i < prices.length; i++) {
        out.writeObject(prices[i]);
        out.writeInt(units[i]);
        out.writeUTF(descs[i]);
      }
    } finally {
      out.close();
    }
    ObjectInputStream in = null;
    try {
      in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(
          dataFile)));
      Calendar date = null;
      BigDecimal price;
      int unit;
      String desc;
      BigDecimal total = new BigDecimal(0);
      date = (Calendar) in.readObject();
      System.out.format("On %tA, %<tB %<te, %<tY:%n", date);
      try {
        while (true) {
          price = (BigDecimal) in.readObject();
          unit = in.readInt();
          desc = in.readUTF();
          System.out.format("You ordered %d units of %s at $%.2f%n", unit,
              desc, price);
          total = total.add(price.multiply(new BigDecimal(unit)));
        }
      } catch (EOFException e) {
      }
      System.out.format("For a TOTAL of: $%.2f%n", total);
    } finally {
      in.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 + "]";
  }
}





Use ObjectOutputStream and ObjectInputStream to write and read Hashtable

 
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) throws Exception {
    Hashtable h = new Hashtable();
    h.put("string", "AAA");
    h.put("int", new Integer(26));
    h.put("double", new Double(Math.PI));
    FileOutputStream fileOut = new FileOutputStream("hashtable.ser");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(h);
      
    FileInputStream fileIn = new FileInputStream("h.ser");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    Hashtable h = (Hashtable)in.readObject(  );
    System.out.println(h.toString(  ));      
  }
}