一,先回顾下传统io
io其实就是为了传输数据流,这时肯定会想,数据流从哪里来,以什么格式传输.即数据存储方式和数据格式.
数据源:
1,字节数组
2,String对象
3,文件
4,管道(PipedInputStream.PipedOutputStream,PipedReader,PipedWriter)
5,Internet
不管数据在哪,读取写入数据的方法都是使用inputStream或reader的子类读取数据,使用outputStream或writer的子类写数据.我们几乎每次都要对输入进行缓冲,不管我们正在连接的是什么I/O设备,无缓冲输入是特殊情况.
下面讨论文件I/O.
1,从文件读取数据
1)一次一个字节读取文件
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream(filename)));//装饰者模式
while(in.available()!=0){
System.out.print((char)in.readByte());
}
2)字符读取
2,往文件写入数据
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(filename)));
二,NIO
NIO使用了通道和缓冲器
1,文件读写:
FileChannel in = new FileInputStream(filename1).getChannel();//这个文件的数据将会输入到buffer里
FileChannel out = new FIleOutputStream(filename2).getChannel();//从buffer里读取数据写入到这个文件里
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);//创建BSIZE大小的缓冲器
//根据需要加入基本类型视图缓冲器,例如IntBuffer ib = buffer.asIntBuffer();
//ByteBuffer是将数据移进移出通道的唯一方式,不能将基本类型的缓冲器转换成ByteBuffer,而是经由视图缓冲器将基本类型数据移进移出ByteBuffer.
while(in.read(buffer)!=-1){//没到文件末尾
buffer.flip();//为写入做准备
out.writer(buffer);
buffer.clear();//为读取做准备
}
或者两个通道也可以直接相连
FileChannel in = new FileInputStream(filename1).getChannel();
FileChannel out = new FIleOutputStream(filename2).getChannel();