对象的写入与写出
这几天学习的Java的输入输出流自己写了一段程序。发现的自己写的程序的太多的BUG与大家分享一下。
1、写出的时候记得强制flush一下,不然由于缓存区未满的原因,写出内容可能无法输出。
2、用ByteArrayOutputStream的时候记得要获取字节数组,再用字节数组初始化输入流。
3、能不要使用内部类最好不好使用内部类,(我把Employ写成内部类的时候,类的初始化出了问题,具体的原因我也没有找到。)
4、注意变量的生命周期,在{}里面定义的变量只在{}有效。
5、要将对象写出类必须实现java.io.Serializable接口。
6、最好自己写异常的处理,不要将其抛出。
package HLJuniversity.RG.Learn.practiceIo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
/**
* 对象的写入写出 对象的序列化和反序列化 不是所有的对象都可以序列化
* @author RG
*
*/
public class LIo_ObjectInputStream {
public static void main(String[] args) {
test01();
}
public static void test01() {
// 写出
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream dos = null;
try {
dos = new ObjectOutputStream(new BufferedOutputStream(baos));
} catch (IOException e) {
e.printStackTrace();
}
// 写基本数据类型
try {
dos.writeInt(20);
dos.writeUTF("bug很多");
} catch (IOException e) {
e.printStackTrace();
}
// 写对象
Employ en= new Employ("小明:",4000);
try {
dos.writeObject("Not thing is impossible!");
dos.writeObject(new Date());
} catch (IOException e1) {
e1.printStackTrace();
}
try {
dos.writeObject(en);
} catch (IOException e2) {
e2.printStackTrace();
}
// 强制flush
try {
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
// 获取字节数组
byte[] datas = baos.toByteArray();
// 读取
ObjectInputStream dis = null;
try {
dis = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
} catch (IOException e) {
e.printStackTrace();
}
int intread = 0;
String str = null;
Object strobject = null;
Object date = null;
Object employee = null;
try {
intread = dis.readInt();
str = dis.readUTF();
strobject = dis.readObject();
date = dis.readObject();
employee = dis.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(intread);
System.out.println(str);
if (strobject instanceof String) {
String strobjectc = (String) strobject;
System.out.println(strobjectc);
}
if (date instanceof Date) {
Date datec = (Date) date;
System.out.println(datec);
}
if (employee instanceof Employ) {
Employ employeec = (Employ) employee;
System.out.println(employeec.getName() + employeec.getSalary());
}
}
}// class LIo_ObjectInputStream 结束
class Employ implements java.io.Serializable{
private String name;
private double salary;
public Employ() {
}
public Employ(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}