ObjectInputStream类和ObjectInputStream类的使用
版权声明:本文为博主原创文章,未经博主允许不得转载。
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);
}
}
ObjectInputStream类和ObjectInputStream类的使用的更多相关文章
- 转:ObjectInputStream类和ObjectInputStream类的使用
ObjectInputStream和ObjectInputStream类创建的对象被称为对象输入流和对象输出流. 创建文件输出流代码: FileOutputStream file_out = new ...
- JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式
相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...
- 【转】UML类图与类的关系详解
UML类图与类的关系详解 2011-04-21 来源:网络 在画类图的时候,理清类和类之间的关系是重点.类的关系有泛化(Generalization).实现(Realization).依赖(D ...
- Java如何解决脆弱基类(基类被冻结)问题
概述 大多数好的设计者象躲避瘟疫一样来避免使用实现继承(extends 关系).实际上80%的代码应该完全用interfaces写,而不是通过extends.“JAVA设计模式”一书详细阐述了怎样用 ...
- 类A have-a 类B,类B访问类A public 成员
需求是类A中包含类B,而类B又需要访问类A的public属性的成员. 首先类B中要访问类A的属性,那么对于类B而言,我们必须要知道有类A这个类,所以在类B的具体实现之前我们需要前向声明类A. 对于类A ...
- UML(一) 类图及类间关系
原创文章,同步发自作者个人博客,http://www.jasongj.com/uml/class_diagram/ UML类图 UML类图介绍 在UML 2.*的13种图形中,类图是使用频率最高的UM ...
- JAVA正则表达式:Pattern类与Matcher类详解(转)
java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包.它包括两个类:Pattern和Matcher Pattern 一个Pattern是一个正则表达式经编译后的表 ...
- C# 根据类名称创建类示例
//获得类所在的程序集名称(此处我选择当前程序集) string bllName = System.IO.Path.GetFileNameWithoutExtension(System.Reflect ...
- 使用date类和format类对系统当前时间进行格式化显示
一:Date------------String 代码1:(代码二对显示出来的时间格式进行优化) package DateDemo; import java.text.SimpleDateFormat ...
随机推荐
- IQueryable和list本地集合区别
详情请看:http://www.cnblogs.com/imust/archive/2012/11/18/2776320.html
- Bete冲刺第三阶段
Bete冲刺第三阶段 今日工作: web: 检索了各类资料,今日暂时顺利解决了hibernate懒加载异常的问题,采用的凡是也比较简单就是添加了一个OpenSessionInViewFilter的过滤 ...
- extjs 箱子布局
a.flex 配置项 flex 配置项不是设置在布局上,而是设置在子项的配置项.每个子项相对的 flex 值都会与全体子项 flex 累加的值相比较,根据此结果,处理每个子项的 flex 最后是多少. ...
- 【转】css布局居中和CSS内容居中区别和对应DIV CSS代码
原文地址:http://www.divcss5.com/jiqiao/j771.shtml css布局居中和CSS内容居中区别和对应DIV CSS代码教程与图文代码案例篇 对于新手来说DIV CSS布 ...
- 使用SFTP工具下载文件
1. 打开SFTP会话 File->Connect SFTP Session 2. cd 到文件目录下 3. get 文件名称 sftp> get catalina.out 4. lpw ...
- 同 一个页面,不同请求路径,如何根据实际场景写JS
场景:使用同一个“添加群成员”的页面来操作 建群页面:建群成功后,返回查看群成员页面.在建群过程中直接添加群成员并返回一个群名称的参数. 添加群成员页面:在巳有群内添加群成员,添加成功后,返回查看群成 ...
- IOS APP开发中View的几种实现方式
xib文件有以下几个重要的属性: xib文件名 File’s Owner xib文件中的视图的Class xib文件中的视图的Outlet指向 File’s Owner 可以关联到某类,然后通过IBO ...
- navigate连接MySQL报错:navigate your password has expired to log in your must change it using a client that supports
如图: 终端进入mysql: 第一次show databases的的时候,密码过期了,然后重置密码为12345,再次就可以显示了 参考连接:http://www.jb51.net/article/79 ...
- C++强制类型转换操作符 const_cast
const_cast也是一个强制类型转换操作符.<C++ Primer>中是这样描述它的: 1.将转换掉表达式的const性质. 2.只有使用const_cast才能将const性质性质转 ...
- 针对CMS中的tag标签理解
针对CMS的tag标签有以下解释: 什么tag标签? TAG标签是一种由自定义的一种标签,要比分类更加的准确,可以概括文章主要内容的关键词. 运用TAG标签,可以使网站的文章更容易被搜索引擎检索到.百 ...