2019独角兽企业重金招聘Python工程师标准>>>

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://my.oschina.net/NEMOCoder/blog/608945

java基础--ObjectInputStream和ObjectInputStream类相关推荐

  1. Java基础语法68-抽象类练习

    Java基础语法68-抽象类练习 编写工资系统,实现不同类型员工(多态)的按月发放工资.如果当月出现某个 Employee对象的生日,则将该雇员的工资增加100元. 实验说明: (1) 定义一个Emp ...

  2. java基础知识-对象和类

    前言: 因为要准备Java面试,所有将java基础知识点重新复习一遍,主要笔记来源于菜鸟教程和java核心技术的书籍中,也有一些博客上的资料(这些只供我个人学习使用) Java 对象和类 对象:对象是 ...

  3. Java面试基础篇之java基础语法之五:类和对象

    目录 1. 类与对象的初步认知 2. 类和类的实例化 3. 类的成员 3.1 字段/属性/成员变量 3.2 方法 (method) 3.3 static 关键字 3.4 小结 4. 封装 4.1 pr ...

  4. Java基础(五)-类的特性

    文章首发及后续更新:https://mwhls.top/1277.html 新的更新内容请到mwhls.top查看. 无图/无目录/格式错误/更多相关请到上方的文章首发页面查看. Java基础目录 这 ...

  5. java基础入门-预定义类与自定义类

    预定义类与自定义类 先上代码 <span style="font-size:14px;">package com.ray.object;import java.util ...

  6. Java基础篇之常用类(1)

    目录 常用API: Scanner: object类: to String()方法: equals()方法: String类: String类创建对象的特点: String练习之模拟用户登录: Str ...

  7. JAVA 基础(4) 类与对象

    Java语言的基本元素: 类和对象 万丈高楼平地起,java也不列外.这篇文章让我们来探索java的独特的魅力类和对象. 面向对象的思想概述 : 类(Class)和对象(Object)是面向对象的核心 ...

  8. Java基础篇:常用类

    文章目录 1.字符串相关的类 1.1 String类及常用方法 String的特性 String对象的创建 字符串对象是如何存储的 String使用陷阱 String常用方法 1.2 StringBu ...

  9. [ 转载 ] Java基础10--关于Object类下所有方法的简单解析

    关于Object类下所有方法的简单解析 类Object是类层次结构的根类,是每一个类的父类,所有的对象包括数组,String,Integer等包装类,所以了解Object是很有必要的,话不多说,我们直 ...

  10. java基础 第6章类再生

    第6章类再生 "Java引人注目的一项特性是代码的重复使用或者再生.但最具革命意义的是,除代码的复制和修改以外,我们还能做多得多的其他事情." 在象C那样的程序化语言里,代码的重复 ...

最新文章

  1. [SQL Server优化]善用系统监视器,确定系统瓶颈
  2. 默认的程序化等效项(类型)
  3. Weblogic10 + EJB3入门教程(1):编写第一个无状态会话Bean(Stateless Session Bean)...
  4. android 动态控制截屏,应用助手for Android新版本:可动态截屏存图
  5. mac中打开nginx位置
  6. 外设驱动库开发笔记37:S1336-5BQ光敏二极管作为光度计驱动
  7. Qt中线程的简单使用
  8. 59. C# -- .NET Framework 常用命名空间总结
  9. log4j mysql 单引号_log4j写数据库存在单引号问题
  10. span标签居中显示的正确方法
  11. 使用Calender类获取系统时间和时间和运算
  12. CA服务器的简单搭建
  13. 关于Matlab生成批量文件文件名统一数字位数方法
  14. sysstat工具包提供的主要命令
  15. HTML(超文本语言)
  16. 黑客张福:互联网是黑暗的森林
  17. 【PBR系列一】PBR知识体系
  18. vue中获取短信验证码IOS手机问题
  19. oracle同步数据adg_[adg数据库同步机制]三分钟读懂Oracle数据库容灾架之DataGuard
  20. oracle 查询group by的字段之外的字段

热门文章

  1. RGB图像转为灰度图像原理
  2. python 对文件夹的相关操作
  3. 压力测试jmeter入门教程
  4. Nginx性能提升--引入线程池性能提升9倍
  5. eclipse没有java web,Java-我的Eclipse IDE中缺少Web服务选项
  6. php留言板源码免mysql_php留言本源码-夏日PHP+Mysql留言本下载 v0.3免费版--pc6下载站...
  7. 今天,我需要你的支持!
  8. 周五,分享一个好消息
  9. 工程图样中粗实线的用途_电气工程图的一般特点、设计规范
  10. php爬取网站所有链接,php 爬取超链接