※ ObjectOutputStream 将对象转化为字节流
package com.briup.IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class ObjectOutputStreamTest {
public static void main(String[] args) {
FileOutputStream fos=null;
ObjectOutputStream oos=null;
try {
fos=new FileOutputStream("src/com/briup/IO/IO1.txt");
//将对象转化为字节流传给fos
oos=new ObjectOutputStream(fos);
Car c=new Car(1,"pass",310000);
//写入的顺序和取出的顺序必须一致
oos.writeObject(c);
oos.writeDouble(334.22);
oos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(fos!=null)fos.close();
if(oos!=null)oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.briup.IO;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
public class ObjectOutPutStreamTest1 {
public static void main(String[] args) {
ByteArrayOutputStream baos=null;
ObjectOutputStream oos=null;
ByteArrayInputStream bais=null;
ObjectInputStream ois=null;
try {
//把对象写入缓存中的字节数组中
baos=new ByteArrayOutputStream();
oos=new ObjectOutputStream(baos);
oos.writeObject(new Car(2,"test",3333));
oos.writeUTF("hello world");
oos.flush();
System.out.println(Arrays.toString(baos.toByteArray()));
//从缓存中的字节数组中读取对象
bais=new ByteArrayInputStream(baos.toByteArray());
ois=new ObjectInputStream(bais);
Car c=(Car) ois.readObject();
System.out.println(c);
String str=ois.readUTF();
System.out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注:Car对象类
package com.briup.IO;
import java.io.Serializable;
public class Car implements Serializable{
private static final long serialVersionUID = -2966467466941003653L;
private long id;
private String name;
//如果在对象在IO传输的过程中希望某些字段自动规避
//(值不可见)
//transient修饰的全局变量在序列化和反序列化过程直接忽略
//掉值
private transient double price;
@Override
public String toString() {
return "Car [id=" + id + ", name=" + name + ", price=" + price + "]";
}
public Car() {
}
public Car(long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}