Java/File Input Output/ObjectOutputStream
Содержание
- 1 A program that serializes and deserializes an Employee array
- 2 Create ObjectOutputStream out of FileOutputStream
- 3 implements Externalizable
- 4 new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(StringFileName)));
- 5 Override writeObject(ObjectOutputStream oos) and readObject(ObjectInputStream ois)
- 6 Returns a byte array from the given object.
- 7 Serializing an Object (JButton)
- 8 Write different data types with ObjectOutputStream
- 9 Writing objects to file with ObjectOutputStream
A program that serializes and deserializes an Employee array
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* A program that serializes and deserializes an Employee array.
*/
public class SerializeEmployeeTester {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Employee[] staff = new Employee[2];
staff[0] = new Employee("Fred Flintstone", 50000);
staff[1] = new Employee("Barney Rubble", 60000);
staff[0].setBuddy(staff[1]);
staff[1].setBuddy(staff[0]);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
"staff.dat"));
out.writeObject(staff);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"staff.dat"));
Employee[] staff2 = (Employee[]) in.readObject();
in.close();
for (Employee e : staff2)
System.out.println(e);
}
}
class Employee implements Serializable {
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
this.buddy = this;
}
public void setBuddy(Employee buddy) {
this.buddy = buddy;
}
public String toString() {
return getClass().getName() + "[name=" + name + ",salary=" + salary
+ ",buddy=" + buddy.name + "]";
}
private String name;
private double salary;
private Employee buddy;
}
Create ObjectOutputStream out of FileOutputStream
/*
* 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.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class CardWriter {
public static void main(String[] args) {
Card3 card = new Card3(12, Card3.SPADES);
System.out.println("Card to write is: " + card);
try {
FileOutputStream out = new FileOutputStream("card.out");
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(card);
oos.flush();
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
}
}
/*
* 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;
}
}
implements Externalizable
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
class Engine implements Externalizable {
private int numCylinders;
public Engine() {
}
Engine(int numCylinders) {
this.numCylinders = numCylinders;
}
int getNumCylinders() {
return numCylinders;
}
public void readExternal(ObjectInput in) throws IOException, ClassCastException {
System.out.println("READ-Engine");
numCylinders = in.readInt();
}
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("WRITE-Engine");
out.writeInt(numCylinders);
}
}
class Car implements Externalizable {
private int numTires;
private Engine e;
private String name;
public Car() {
}
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;
}
public void readExternal(ObjectInput in) throws IOException, ClassCastException {
System.out.println("READ-Car");
numTires = in.readInt();
name = in.readUTF();
try {
e = (Engine) in.readObject();
} catch (ClassNotFoundException e) {
}
}
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("WRITE-Car");
out.writeInt(numTires);
out.writeUTF(name);
out.writeObject(e);
}
}
class EDemo {
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());
}
}
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(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();
}
}
}
Override writeObject(ObjectOutputStream oos) and readObject(ObjectInputStream ois)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Employee implements Serializable {
private String name;
private double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
String getName() {
return name;
}
double getSalary() {
return salary;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
System.out.println("Serializing Employee object\n");
}
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
salary += 100;
System.out.println("Deserializing Employee object");
}
}
class Main {
public static void main(String[] args) throws Exception {
Employee e1 = new Employee("A", 45000.0);
System.out.println(e1.getName() + " " + e1.getSalary());
FileOutputStream fos = new FileOutputStream("employee.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e1);
FileInputStream fis = new FileInputStream("employee.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Employee e2 = (Employee) ois.readObject();
System.out.println(e2.getName() + " " + e2.getSalary());
}
}
Returns a byte array from the given object.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Main {
/**
* Returns a byte array from the given object.
*
* @param object
* to convert
* @return byte array from the object
*/
public static byte[] objectToBytes(Object object) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(object);
return baos.toByteArray();
}
}
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));
}
}
Write different data types with ObjectOutputStream
/*
* 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();
}
}
}
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);
}
}