Java数据流 过滤流,管道数据流
过滤流
1.缓冲区数据流
缓冲区数据流有BufferedInputStream和BufferedOutputStream,
默认缓冲区大小
FileInputStream fis = new FileInputStream("myfile"); InputStream is = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("myfile"); OutputStream os = new BufferedOutputStream(fos);
自己设置缓冲区大小
FileInputStream fis = new FileInputStream("myfile"); InputStream is = new BufferedInputStream(fis,1024); FileOutputStream fos = new FileOutputStream("myfile"); OutputStream os = new BufferedOutputStream(fos,1024);
这里需要注意的是,在关闭一个缓冲区输出流之前,要使用flush()方法,强制输出剩余数据,确保缓冲区里的所有数据全部写入输出流
2.数据数据流
之前说的数据流中,处理的数据不是字节就是字节数组,但是有很多时候,不只是只有这两种数据,所以就要用专门的过滤流数据流来处理,这里给出
DataInputStream,DataOutputStream, 他们允许对Java基本类型进行处理,
在DataInputStream类中,提供了下面这些方法:对基本类型进行读取
byte readByte()
long readLong()
double readDouble()
boolean readBoolean()
String readUTF()
int readInt()
float readFloat()
short readShort()
char readChar()
在DataOutputStream类中,这些方法对基本类型的数据进行写入。
void writeByte(int aByte)
void writeUTF(String aString)
后面的与之前的类似,在这里不做过多说明
这里需要注意的是,对字符串的读写方法,应当使用Reader and Writer中的方法,避免使用readUTF(), writeUTF(String aString)
2.管道数据流
管道的两端建立连接后就可以通信了
import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class PipedStreamDemo { public static void main(String args[])throws IOException { //建立管道连接 PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); //数据赋值 byte datamover = 0; System.out.println("start work..."); try{ System.out.println("transfer "+ datamover +" to pos.\n"); //写入数据 pos.write(datamover); //读取数据 System.out.println("pis get "+(byte)pis.read()); }finally{ pis.close(); pos.close(); } } }
3.对象流
将一个对象示例写入文件
import java.io.*; import java.util.Date; public class DataTest { public static void main(String args[]){ Date d = new Date(); FileInputStream f = new FileInputStream("date.ser"); ObjectOutputStream s = new ObjectOutputStream(f); try{ s.writeObject(d); s.close(); }catch(IOException e){ e.printStackTrace(); } } }
4.可持久化
可持久化就是对象通过描述自己状态的数值来记录自己的过程
当一个类实现Serializable接口时,表明该类加入了对象串行化协议
在Java中,允许可串行化的对象通过对象流进行传输
对象结构表
串行化只能保存对象的非静态成员变量,有一些对象类不具有可持久性,比如Thread对象 或者 流对象,
这样的成员变量就需要使用 transient 关键字标明,不然编译器会报错。
任何用transient标明的成员变量,都不会被保存,比如在一些保密的数据上,就非常需要这个transient 关键字来标明