liuzhaomin 发表于 2013-2-7 08:23:57

Java NIO入门

 
package com.ls.java.newio;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class CopyFile {public static void main(String[] args) {String infile = "/home/astute/comm/01_select.sql";String outfile = "/home/astute/comm/copy_to_new.sql";try {// 获取源文件和目标文件的输入输出流FileInputStream is = new FileInputStream(infile);FileOutputStream os = new FileOutputStream(outfile);// 获取输入输出通道FileChannel fcin = is.getChannel();FileChannel fcout = os.getChannel();// 创建缓冲区ByteBuffer buffer = ByteBuffer.allocate(1024);while(true) {// clear方法重设缓冲区,使它可以接受读入的数据buffer.clear();// 从输入通道中将数据读到缓冲区int r = fcin.read(buffer);// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1if(r == -1)break;// flip方法让缓冲区可以将新读入的数据写入另一个通道// 写模式转换成读模式buffer.flip();// 从输出通道中将数据写入缓冲区fcout.write(buffer);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}} 
Buffer常见方法:
flip():写模式转换成读模式
rewind():将position重置为0,一般用于重复读。
clear():清空buffer,准备再次被写入(position变成0,limit变成capacity)。
compact():将未读取的数据拷贝到buffer的头部位。
mark()、reset():mark可以标记一个位置,reset可以重置到该位置。
Buffer常见类型:ByteBuffer 、MappedByteBuffer 、CharBuffer 、DoubleBuffer 、 FloatBuffer 、 IntBuffer 、 LongBuffer 、 ShortBuffer。
 
 
 
 
 
页: [1]
查看完整版本: Java NIO入门