InputStream\OutputStream\Reader\Writer

InputStream\OutputStream\Reader\Writer构成了java.io的鼻祖。
具体如下:
InputStream和OutputStream类仅仅读取和写入单个的字节和字节数组,它们没有读取和
写入字符串和数值的方法。
对于Unicode文本,一个字符占用两个字节,所以出现了Reader和Writer。
特别:ZipInputSteam和ZipOutputStream能读写常见的ZIP压缩格式的文件。
InputStream、OutputStream、Reader、Writer类都实现了Closeable接口。
OutputStream和Writer都实现了Flushable接口。
FileInputStream和FileOutputStream能够把输入和输出流与磁盘文件关联起来。
eg:
FileInputStream fin = new FileInputStream("c:\\dev\\my.dat");------注意:最好使用反斜杠,反斜杠代表转义符使用。
或者:
File f = new File("c:\\dev\\my.dat');
FileInputStream fin = new FileInputStream (f);
用于读取字节:
byte b = (byte)fin.read();
用于读取数值:
DataInputStream dis = new DataInputStream(fin);
double d = dis.readDouble();
FileInputStream没有读取数值的能力,但是DataInputStream也没有从文件中读取数值的方法,所以两者注定在一起结合使用!
从上面我们可以知道:
java的处理IO的两种策略:一些流(如FileInputStream)可以从文件及其他地方接收字节;另一些流(如DataInputStream和PrintWriter)可以将字节组合成更加有用的数据类型。
eg:
FileInputStream fin = new FileInputStream("c:\\dev\\my.dat");---------从文件中读取值,创建流
DataInputStream dis = new DataInputStream(fin); --------结合后的流叫:过滤流(filtered stream)
double d = dis.readDouble();
默认情况下,流是不能进行缓冲处理的。就是每次对流进行read读取都要求操作系统发送一个新字节,若想要对当前目录下的文件
进行缓冲和数据输入操作,应该利用FileInputStream和FileOutputStream它们的子类合并为一个新的过滤流。
DataInputStream dis= new DataInputStream(new BufferedInputStream(new FileInputStream("c:\\dev\\my.dat")));
PushbackInputStream pis = new PushbackInputStream(new BufferedInputStream(new FileInputStream("c:\\dev\\my.dat")));-------能够对流进行跟踪,如下:
int b = pis.read(); -----读取下一个字节
if(b != '<') pis.unread(b);--------不是自己想要的,把它扔回去
但是read和unread是PushbackInputStream仅有的方法,若既想预查看,又想获取值,可以用:
DataInputStream dis= new DataInputStream(
pis = new PushbackInputStream(new BufferedInputStream(new FileInputStream("c:\\dev\\my.dat")));
利用构造的真正实用的流序列,也为我们带来很大的灵活性。
处理zip文件:
ZipInputStream zip = new ZipInputStream(new FileInputStream("ocean.zip"));
DataInputStream dis = new DataInputStream(zip);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值