学习地址:http://ifeve.com/overview/
基本例子:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
//使用FileChannel读取数据到buffer,从buffer写入数据到FileChannel
public class FileChannel {
public static void main(String[] args) throws IOException {
RandomAccessFile aFile=new RandomAccessFile("/Users/bjhl/test.txt","rw");
java.nio.channels.FileChannel inChannel=aFile.getChannel();
ByteBuffer buf=ByteBuffer.allocate(48);
int bytesRead=inChannel.read(buf);//写数据到buffer,返回写入的总字节数
while(bytesRead!=-1){//若读到了-1,表示到达了文件尾
System.out.println("Read "+bytesRead);
buf.flip();//将buffer的写模式切换为读模式
while(buf.hasRemaining()){
System.out.print((char)buf.get());//读buffer数据
}
buf.clear();//清空缓冲区,让它可以再次被写入(其实数据并未清除,只是position设置为0,limit设置为capacity的值)
bytesRead=inChannel.read(buf);
}
//写数据到channel
String newData="New String to write to file..."+System.currentTimeMillis()+"\n";
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()){
inChannel.write(buf);
}
aFile.close();
}
}