Channel的基本使用

来源:互联网 发布:淘宝卖家发货 具体流程 编辑:程序博客网 时间:2024/06/07 23:03
import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class ReadFile {     public static void main(String[] args) throws IOException {    /*    FileInputStream fis=new FileInputStream("c:\\jdk\\b.txt");          FileOutputStream fos=new FileOutputStream("c:\\jdk\\d.txt");          FileChannel fco=fos.getChannel();//该channel只能写,读写文件用channel          FileChannel fc=fis.getChannel();//该channel只能读          ByteBuffer bb=ByteBuffer.allocate(100);//channel必须和buffer联系          while(fc.read(bb)!=0) {              bb.flip();              fco.write(bb);              bb.clear();          }          fis.close();          fos.close();          */         File f=new File("c:\\jdk\\b.txt");          RandomAccessFile raf=new RandomAccessFile(f, "rw");          raf.seek(f.length());          FileChannel rafc=raf.getChannel();          /** i. 使用InputStream获得的Channel可以映射,使用map时只能指定为READ_ONLY模式,不能指定为READ_WRITE和PRIVATE,否则会抛出运行时异常!             ii. 使用OutputStream得到的Channel不可以映射!!并且OutputStream的Channel也只能write不能read!             iii. 只有RandomAccessFile获取的Channel才能开启任意的这三种模式!*/          ByteBuffer bbb=rafc.map(FileChannel.MapMode.READ_ONLY, 0,f.length());        // rafc.position(f.length());//相当于seek          System.out.println( raf.getFilePointer());          rafc.write(bbb);     }}
原创粉丝点击