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方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if(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 。