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

}

}

转载于:https://www.cnblogs.com/zhangshitong/p/5197610.html

转:ObjectInputStream类和ObjectInputStream类的使用相关推荐

  1. Java常用类(Object类及它的常用方法)

    常见对象(API概述以及Object类的概述) API(Application Programming Interface) 应用程序编程接口 Java API 就是Java提供给我们使用的类,这些类 ...

  2. Java基础IO流概述、字符流、字节流、流操作规律、File类、Properties类、打印流、序列流

    IO流:(Input Output)流 字符流的由来:其实就是字节流读取文字字节数据后,不直接操作而是先查指定的码表,获取对应的文字进行操作 简单说:字符流 = 字节流 + 编码表 字节流的两个顶层父 ...

  3. python中的新式类与旧式类的一些基于descriptor的概念(上)

    python中基于descriptor的一些概念(上) 1. 前言 2. 新式类与经典类 2.1 内置的object对象 2.2 类的方法 2.2.1 静态方法 2.2.2 类方法 2.3 新式类(n ...

  4. C++ 笔记(16)— 类和对象(类定义、类实例对象定义、访问类成员、类成员函数、类 public/private/protected 成员、类对象引用和指针)

    1. 类的定义 类定义是以关键字 class 开头,后跟类的名称.并在它后面依次包含类名,一组放在 {} 内的成员属性和成员函数,以及结尾的分号. 类声明将类本身及其属性告诉编译器.类声明本身并不能改 ...

  5. java 类定义_JAVA类与对象(二)----类定义基础

    类是组成java程序的基本要素,是java中的一种重要的复合数据类型.它封装了一类对象的状态和方法,是这一类对象的原型.一个类的实现包括两个部分:类声明和类体,基本格式: class { 属性 方法 ...

  6. C++派生类与基类构造函数调用次序

    本文用来测试C++基类和派生类构造函数,析构函数,和拷贝构造函数的调用次序. 运行环境:SUSE Linux Enterprise Server 11 SP2  (x86_64) #include & ...

  7. python 类中定义类_Python中的动态类定义

    python 类中定义类 Here's a neat Python trick you might just find useful one day. Let's look at how you ca ...

  8. Java 常用对象-Date类和Calender类

    2017-11-02 22:29:34 Date类:类 Date 表示特定的瞬间,精确到毫秒. 在 JDK 1.1 之前,类 Date 有两个其他的函数.它允许把日期解释为年.月.日.小时.分钟和秒值 ...

  9. C++中基类与派生类的构造函数和析构函数

    1.Cpp中的基类与派生类的构造函数 基类的成员函数可以被继承,可以通过派生类的对象访问,但这仅仅指的是普通的成员函数,类的构造函数不能被继承.构造函数不能被继承是有道理的,因为即使继承了,它的名字和 ...

最新文章

  1. linux文件操作篇 (一)文件属性与权限
  2. CYQ.Data 轻量数据层之路 使用篇三曲 MAction 取值赋值(十四)
  3. 大话设计模式--建造者模式 Builder -- C++实现实例
  4. 来自微博html5怎么设置,来自微博的面试题解决方案
  5. LmgORM项目: 介绍
  6. 剑指offer--剪绳子
  7. java经典设计模式4,JAVA设计模式(4) 之装饰设计模式
  8. grunt之Gruntfile(1)
  9. dlib+vs2013+opencv实现人脸特征点检测
  10. python怎么在字符串里加入变量数字_Python学习笔记(一)之基本元素:变量,数字和字符串...
  11. Java中的两种异常类型及其区别?
  12. exec go 重启_[译]Golang中的优雅重启
  13. linux 挂载windows共享目录 is not a valid block device
  14. SolidWorks工程图导出PDF时出现“Arial Unicode MS”字体不存在时,解决方案
  15. html自动随机跳转网址,网页随机跳转代码
  16. 渗透测试工程师字典介绍
  17. 2021年下半年软件设计师上午真题答案及解析(三)
  18. sam格式的结构和意义_SAM文件是什么
  19. 量子计算机读后感,《天才的拓荒者:冯·诺伊曼传》- 读后感
  20. 批量复制提取Word中所有的表格到Excel(Python办公自动化)

热门文章

  1. 云中漫步 - 3:2013-4-27 微软云体验营北京站
  2. 仿Drinkspiration App的menu
  3. 克服Dropout缺陷,简单又有效的正则方法:R-Drop
  4. Transformer 杀疯了,图像去雨、人脸幻构、风格迁移、语义分割等通通上分
  5. 多媒体领域顶会,ACM MM 2020 会议论文下载
  6. 香港中文大学(深圳)张大鹏教授访谈
  7. BBAug: PyTorch的物体检测包
  8. 火爆全网络!这个GitHub项目开源了!搞定目标检测、图像识别
  9. 收藏 | 彻底搞懂机器学习中的正则化
  10. GitHub上已超过2900星!这份有原理、有代码、有Demo的算法资源火了