使用通道来传输文件

public class channel_test {app

public static void main(String[] args) throws Exception {

store_map(); }操作系统

//采用内存映射的方式读写文件

 public static void store_map() throws Exception{
 
  FileChannel in = FileChannel.open(Paths.get("d:/test/aa.txt"), StandardOpenOption.READ);
  
  FileChannel out= FileChannel.open(Paths.get("d:/test/aa_copy.txt"),StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);

   //创建内存映射文件 这个咱们就没法对其进行操做,有操做系统来负责
     MappedByteBuffer src=in.map(FileChannel.MapMode.READ_ONLY,0,in.size());
     MappedByteBuffer des = out.map(FileChannel.MapMode.READ_WRITE,0,in.size());

     //对映射文件进行操做
     byte b[]=new byte[src.limit()];
     src.get(b);
     des.put(b);

     in.close();
     out.close();

 }

//采用非直接内存映射的方式
public static void non_store() throws Exception{
    //用于源节点与目标节点的链接。在nio中负责缓冲区的传输
    FileInputStream src=new FileInputStream("d:/test/a.txt");
    FileOutputStream des = new FileOutputStream("d:/test/c_copy.txt");

    //创建通道
    FileChannel in = src.getChannel();
    FileChannel out=des.getChannel();

    //创建缓冲区
    ByteBuffer b=ByteBuffer.allocate(1024);

    //开始对数据
    while (in.read(b)!=-1){
        //切换模式
        b.flip();
        //写数据
        out.write(b);
        ///清空缓冲区
        b.clear();

    }

    out.close();
    in.close();
    des.close();
    src.close();

}

}code

相关文章
相关标签/搜索