黑马程序员-JAVA学习第7课--包装类

来源:互联网 发布:梦里花落知多少上一句 编辑:程序博客网 时间:2024/05/22 14:50

ObjectInputStream 和ObjectOutputStream这两个包装类,用于从底层输入流中读取对象类型的数据和将对象类型的数据写入到底层输出流。

ObjectInputStream与ObjectOutputStream类所读写的对象必须实现了Serializable接口才能使用。

它不会写入transient和static类型的成员变量不会被读取和写入。

 

一个可以被序列化的MyClass类的定义:

public class MyClass implements Serializable

{

   public transient Thread t;

   private String customerID;

   private int total;

}

 

编程举例:创建一个可序列化的学生对象,分别用两个包装类存储和读取。

 

Student.java

import java.io.Serializable;


public class Student implements Serializable {
 int id;
 String name;
 int age;
 String department;
 public Student(int id,String name,int age,String department)
 {
  this.id=id;
  this.name=name;
  this.age=age;
  this.department=department;
 }
}

Serialization.java

 

import java.io.*;
public class Serialization {
 
 /**
  * Method main
  *
  *
  * @param args
  *
  */
 public static void main(String[] args) throws Exception{
  // TODO: 在这添加你的代码
  Student stu1=new Student(12,"zhangsan",29,"huaxue");
  Student stu2=new Student(13,"lishi",24,"wuli");
  
  FileOutputStream fos=new FileOutputStream("student.txt");
  
  ObjectOutputStream os=new ObjectOutputStream(fos);
  
  os.writeObject(stu1);
  os.writeObject(stu2);
  
  os.close();
  
  FileInputStream fis=new FileInputStream("student.txt");
  ObjectInputStream ois=new ObjectInputStream(fis);
  stu1=(Student)ois.readObject();
  stu2=(Student)ois.readObject();
  
  ois.close();
  
  System.out.println("id:"+stu1.id+" name:"+stu1.name+" age"+stu1.age+
   " department:"+stu1.department);
  System.out.println("id:"+stu2.id+" name:"+stu2.name+" age"+stu2.age+
   " department:"+stu2.department);
  
 } 
}

 

===============================

字节流与字符流的转换

 InputStreamReader 和OutputStreamWriter,用于将字节流转换成字符流来读写两个类。

InputStreamReader的两个主要构造函数:

 

inputStreamReader(inputStreamin) 

inputStreamReader(inputStreamin,String CharsetName)

 

OutputStreamWriter 的两个主要的构造函数

OutputStreamWriter(OutputStream out)

OutputStreamWriter(OutputStream out,String CharsetName)

 

应避免频繁地在字符与字节间转换,最好不要直接使用InputStreamReader和OutputStream而是用bufferredwriter包装OutputStreamWriter类,用BufferedReader类包装InputStreamReader.

 

 

原创粉丝点击