文件通道流两个实例

来源:互联网 发布:各国出口结构知乎 编辑:程序博客网 时间:2024/04/30 05:09
1.  两句话实现复制,通道连接
  1. package com.eshore.sweetop.io;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.nio.channels.FileChannel;
  5. public class TransferTo {
  6.     public static void main(String[] args) throws Exception {
  7.         FileChannel in = new FileInputStream("test.out").getChannel(), out = new FileOutputStream(
  8.                 "test.out.bak").getChannel();
  9.         in.transferTo(0, in.size(), out);
  10.     }
  11. }

2. 映射内存文件

  1. import java.io.RandomAccessFile;
  2. import java.nio.ByteBuffer;
  3. import java.nio.channels.FileChannel;
  4. import java.nio.channels.FileChannel.MapMode;
  5. public class TestChannel {
  6.     public static void main(String[] args) throws Exception {
  7.         FileChannel fc=new RandomAccessFile("test.out","rw").getChannel();
  8.         ByteBuffer cb=fc.map(MapMode.READ_WRITE, 0, fc.size());
  9.         byte[] b=new byte[cb.capacity()];
  10.         for (int i = 0; i < b.length; i++) {
  11.             b[i]=cb.get(i);
  12.         }
  13.         System.out.println(new String(b));
  14.     }
  15. }