ObjectInputStream和ObjectInputStream类创建的对象被称为对象输入流和对象输出流。
创建文件输出流代码:
FileOutputStream file_out = new FileOutputStream(“student.dat”);
ObjectOutputStream object_out = new ObjectOutputStream(file_out);
创建文件输入流代码:
FileInputStream file = new FileInputStream( "student.dat ");
ObjectInputStream ois = new ObjectInputStream(file);
问题描述:
向一个文件中写入一个对象,可以用ObjectOutputStream套接FileOutputStream来实现(序列化)。但如果想向一个文件中写入多个对象并且能够正确读出来,用它们该如何实现?一种方法是在FileOutputStream和ObjectOutputStream之间再套接一个BufferedInputStream,每写入一个对象,换一行,再写个对象,再换一行。读取的时候,同样在中间套接个FileInputStream,每读一行,读出一个对象,再读一行,又读出个对象。然而这种方法非常的繁琐,且效率低。
知识储备:
使用对象流写入或读入对象时,要保证对象是序列化的。这是为了保证能把对象写入到文件,并能再把对象读回到程序中的缘故。一个类如果实现了Serializable接口,那么这个类创建的对象就是所谓序列化的对象。所谓“对象序列化”: 简单一句话:使用它可以象存储文本或者数字一样简单的存储对象。一个应用是,程序在执行过程中突然遇到短电或者其他的故障导致程序终止,那么对象当前的工作状态也就会丢失,这对于有些应用来说是可怕的。用对象序列化就可以解决这个问题,因为它可以将对象的全部内容保存于磁盘的文件,这样对象执行状态也就被存储了,到需要时还可以将其从文件中按原样再读取出来,这样就解决了数据丢失问题。对象序列化可以简单这么实现:为需要被序列化的对象实现Serializable接口,该接口没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。
上述问题解决方法:
该对象首先要可序列化,然后把多个对象存储到容器里,如ArrayList<?> list;
然后把list序列化存储,读出来就是一串对象了。
例子一:参考资料http://dev.csdn.net/article/31/31129.shtm,
http://zhidao.baidu.com/question/26665922.html?si=4
import java.io.*;
import java.util.*;
public class ObjectFileTest
{
public static void main(String[] args)
{
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
boss.setBonus(5000);
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 15);
staff[2] = new Employee("Tony Tester", 40000, 1990, 1, 15);
try
{
/**
*使用文件输出流构造一个对象输出流
*FileOutputStream文件输出流
*ObjectOutputStream对象输出流
*/
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("employee.dat"));
out.writeObject(staff); //将对象写入"employee.dat"中
out.close(); //关闭流,请牢记
/**
*使用文件输入流构造一个对象输入流
*FileInputStream文件输入流
*ObjectInputStream对象输入流
*/
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("employee.dat"));
///readObject()将对象从"employee.dat"中读出,需要类型转换
Employee[] newStaff = (Employee[])in.readObject();
in.close();
for (int i = 0; i < newStaff.length; i++)
System.out.println(newStaff[i]);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
///implements Serializable接口为标注该对象是可序列化的
class Employee implements Serializable
{
public Employee() {}
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar =
new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name = "+ name
+ ",salary = "+ salary
+ ",hireDay = "+ hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
class Manager extends Employee
{
public Manager(String n, double s, int year, int month, int day)
{
super(n, s, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
public String toString()
{
return super.toString()
+ "[bonus = "+ bonus
+ "]";
}
private double bonus;
}
例子二:
//*********下面是序列化的代码*******
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args)
{
Student[] student ={new Student( "student1 ",22, "男 "),
new Student( "student2 ",21, "女 "),
new Student( "student3 ",20, "男 "),
new Student( "student4 ",19, "女 "),
new Student( "student5 ",18, "男 "),
new Student( "student6 ",17, "男 "),
new Student( "student7 ",22, "女 "),
new Student( "student8 ",22, "女 "),
new Student( "student9 ",22, "女 "),
new Student( "student10 ",22, "男 "),};
try
{
//写入文件
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream( "haoguicai000.txt "));
oos.writeObject(student);//这里存的是数组对象,你也可以用循环把每一个Student对象写进去。
oos.close();
//从文件中读出对象
Student[] students2;
FileInputStream file = new FileInputStream( "haoguicai000.txt ");
ObjectInputStream ois = new ObjectInputStream(file);
students2 = (Student[])ois.readObject();
for(Student s :students2)
{
System.out.println( "姓名: "+s.getName());
System.out.println( "年龄: "+s.getAge());
System.out.println( "性别 "+s.getSex());
}
/*while(file.available()> 0)
System.out.println(((Student)ois.readObject()).getName()); 法二*/
ois.close();
file.close();
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
}
例三:
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
class Student implements Serializable
{
int id;
String name;
int score;
Student(int id,String name,int score)
{
//创建一个学号为id,姓名为name,成绩为score的学生对象
setId(id);
setName(name);
setScore(score);
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return this.id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setScore(int score)
{
this.score=score;
}
public int getScore()
{
return score;
}
}
/*************************************/
public class ScoreSort
{
Scanner scanner;
Student[] student;
int number;
File filename;
public ScoreSort()
{
System.out.print("输入学生的个数:/n");
scanner=new Scanner(System.in);
number=scanner.nextInt();
try
{
if(number<=0) throw new NegativeException();
input(number);
writeToFile(student);
}
catch(NegativeException e)
{
JOptionPane.showMessageDialog(null,"人数小于1!");
}
}
public void input(int n)
{
student=new Student[n];
// System.out.println("学号 姓名 成绩");
for(int i=0;i<student.length;i++)
{ //输入学生的信息
int j = i+1;
System.out.println("输入第"+ j +"个学生");
System.out.println("学号");
int id=scanner.nextInt();
System.out.println("姓名");
String name=scanner.next();
System.out.println("成绩");
int score=scanner.nextInt();
System.out.println("___________________");
student[i]=new Student(id,name,score);
}
}
public void writeToFile(Student[] s)
{
try
{
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream( "student.dat "));
oos.writeObject(student);//这里存的是数组对象,你也可以用循环把每一个Student对象写进去。
oos.close();
}
catch(IOException ex)
{
System.out.println("写入文件失败!");
}
}
}
/***************************************************/
public class ScoreSort2
{
int number=100;
Student student[];
File filename;
public ScoreSort2()
{
output();
student=new Student[number]; //限定学生人数
student=readFromFile();
sort(student);
System.out.println("排序后:");
writeToFile(student);
output();
}
public void sort(Student s[])
{
Student temp = null;
for(int i=0;i<s.length;i++)
{
for(int j=0;j<s.length;j++)
{
if(s[j].getScore()<s[i].getScore())
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
}
public Student[] readFromFile()
{
//将文件内容读入到数组并返回数组
Student[] s=null;
try
{
//从文件中读出对象
Student[] students2;
FileInputStream file = new FileInputStream( "student.dat ");
ObjectInputStream ois = new ObjectInputStream(file);
s = (Student[])ois.readObject();
System.out.println("i am well");
/*while(file.available()> 0)
* System.out.println(((Student)ois.readObject()).getName()); 法二*/
ois.close();
file.close();
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return s;
}
public void writeToFile(Student[] s)
{ //将数组s写入到文件student.dat中
try
{
ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream("student.dat"));
output.writeObject(s);
output.close();
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null,"写入文件失败!");
}
}
public void output()
{
Student[] s3=null;
try
{
ObjectInputStream input=new ObjectInputStream(new FileInputStream("student.dat"));
System.out.println("输出文件student.dat的内容:");
s3 = (Student[])input.readObject();
for(Student s :s3)
{
System.out.println( "学号: "+s.getId());
System.out.println( "姓名: "+s.getName());
System.out.println( "成绩 "+s.getScore());
}
input.close();
}
catch(IOException ex)
{
System.err.println("打开文件失败!");
}
catch(ClassNotFoundException ex)
{
System.err.println("ERROR");
}
}
}
/***************************/
class NegativeException extends Exception
{
NegativeException(){}
public String toString()
{
return "数字是小于或等于0";
}
}
/**********************************/
public class Test
{
public static void main(String[] args)
{
/*ScoreSort scoresort=new ScoreSort();
System.exit(0);*/
ScoreSort2 scoresort2=new ScoreSort2();
System.exit(0);
}
}