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 ...
随机推荐
- Competition-based User Expertise Score Estimation-20160520
1.Information publication:sigir 2011 author:Jing Liu Harbin Institute of TechnologyMicrosoft Researc ...
- 图片上传和显示——上传图片——上传文件)==ZJ
http://www.cnblogs.com/yc-755909659/archive/2013/04/17/3026409.html aspx上传 http://www.cnblogs.com/mq ...
- Day Five (beta)
站立式会议 站立式会议内容总结 331 今天:爬虫抓取豆瓣数据; 明天:数据展示在话题详情页,话题页修改 442 今天:了解聊天模块 遇到的问题:无 明天:编写聊天模块 439 今天:学习 遇到困难 ...
- canvas缓动2
同之前的缓动原理.这里将终点换成鼠标,做出跟随效果 var canvas = document.getElementById("canvas"); var cxt=canvas.g ...
- Java反射机制学习与研究
Java反射机制:可以获取正在运行时的Java对象. 1.判断运行时对象对象所属的类. 2.判断运行时对象所具有的成员变量和方法. 3.还可以调用到private方法,改变private变量的值. S ...
- [转]fastjson常见问题
转自fastjson wiki说明文档:https://github.com/alibaba/fastjson/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98 1. ...
- iOS开发小技巧--巧用ImageView中的mode(解决图片被拉伸的情况)
一.自己遇到的问题:在布局ImageView的时候,通过约束将ImageView布局好,但是里面的图片被拉伸的很难看.这时候就用到了Mode属性,如图: 代码实现方式: 二.让图片按照比例拉伸,并不是 ...
- jQ插件--时间线插件和拖拽API
这个时间轴是工作上用到的,自己写了一个, qq空间有时间轴的控件, 百度文库也有时间轴的控件: 百度的时间轴大概是这样的: 用户点击对应的锚链接, 那个三角会滚动, 然后左侧的界面也会滚动: 实际的 ...
- 数据库开发基础-SQl Server 基础
SQL Server 基础 1.什么是SQL Server SQL:Structured Query Language 结构化查询语言 SQL Server是一个以客户/服务器(c/s)模式访问.使 ...
- MVP模式
一.软件设计鼻祖MVC 1.1.MVC 第一次听到MVC这个名词是在C#中,相信对于MVC大家都已经很熟悉了,作为一种软件设计模式,MVC这个概念已经诞生好多年了. 如果你已经开发一段时间的iOS应用 ...