使用通道來傳輸文件

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

相關文章
相關標籤/搜索