一、ObjectInputStream与ObjectOutputStream
处理字节的直接操作对象的输入、输出流,流的特点是可以直接操作数据的,现在数据被封装成对象了,而对象本身存在堆内存中,当程序结束时,堆内存释放,对象就不存在了,所以讲堆内存中的对象存放在硬盘中,对象中封装的数据会存放在硬盘中,所以重新启动时,讲对象从硬盘中读出来,也就是对象的持久化或对象的序列化。能操作对象的流ObjectOutputStream,再通过ObjectInputStream读。
1、构造方法ObjectOutputStream(OutputStream out)创建写入制定OutputStream的ObjectOutputStream.
2、writeInt与write(Int val)方法的区别
write(Int val)写出的是INT型的最低8位
writeInt讲4个8位都写出去。,可以操作基本数据类型
示例:
import java.io.*;
calss ObjectStreamDemo{
public static void main(String[] args){
writeObj();
readObj();
}
public static void readObj(){
ObbjectInputString ois=new ObbjectInputString(new FileInputStream("obj.txt"));
Person p=(Person)ois.readObject();
System.out.println(p);
ois.close();
}
public static void writeObj(){
ObjectOutputStream oos=new ObjectOutputSteam(new FileOutputStream("obj.txt"));
oos.writeObj("lisi","39","kr");
oos.close();
}
}
//将person类封装起来
import java.io.*;
class Person implements Serializable{
public static final long serialVersionUID=42L;//自定义序列号,给类用于标记用的。保证当Person 改变时序列号不变,可以直接读出文件中的Person 类里的内容
transient String name;//对非静态成员不想被序列化,加transient即可保证其值在堆内存中存在且不能被序列化。
int age;
static String country="cn";//country是共性的不希望改变,static是不能被序列花的,因为静态在方法区不在堆里。
Person(String name,Int age,String country){
this.name=name;
this.age=age;
this.country=country;
}
public String toString(){
return name+":"+age":"+country;
}
}
二、管道流
PipedInputStream和PipedOutputStream输入输出可以直接进行连接,通过结合线程使用,涉及到多线程的IO流。
问题:读和写哪个先执行?应该先写再读。管道输入流应该连接管道输出流,管道输入流提供输出流的所有字节,通常数据由某个线程从PipedOutputStream读取,并由其他线程将其写入到相应的PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将该读操作和写操作分离开。read方法是阻塞式方法,没用要读的时会线程等待,当录入是将线程唤醒。
两个流如何连接呢?
1、PipedInputStream(PipedOutputStream pos)//创建PipedOutputStream,使其连接到管道输出流src。
2、PipedInputStream();connnect(PipedOutputStream pos);
示例:
import java.io.*;
class Read implements Runnable{
private PipedInputStream in;
Read(PipedInputStream in){
this.in=in;
}
public void run(){
try{
byte[] buf=new byte[1024];
int len=in.read(buf);
String s=new String(buf,0,len);
System.out.println(s);
in.close();
}
catch(IOException e){
throw new RuntimeException("管道流读取失败");
}
}
}
class Write implements Runable{
private PipedOutputStream out;
Write(PipedOutputStream out){
this.out=out;
}
public void run(){
try{
out.write("piped lai le");
}
catch(IOException e){
throw new RuntimeException("管道流输出失败");
}
}
}
class PipedStreamDemo{
public static void main(String[] args) throw IOException{
PipedInputStream in=new PipedInputStream();
PipedOutputStream out=new PipedOutputStream();
in.connect(out);
Read r=new Read(in);
Write w=new Write(out);
new Thread(r).start();
new Thread(w).start();
}
}
三、