Channel: 它是一个可以读写数据的通道,相当于IO流,但是与IO流有所不同,通道不区分输入和输出(是双向的)
channel的分类:
FileChannel 文件通道(用于读写文件)
SocketChannel TCP协议客户端通道
ServerSocketChannel TCP协议服务器通道
public class ByteBufferCopy { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream("111.txt"); FileOutputStream fileOutputStream = new FileOutputStream("copt.txt"); //获取ByteBuffer FileChannel ichannel = fileInputStream.getChannel(); FileChannel ochannel = fileOutputStream.getChannel(); //创建Channl ByteBuffer allocate = ByteBuffer.allocate(1024); int len = 0; while ((len = ichannel.read(allocate)) != -1) { allocate.flip(); ochannel.write(allocate); allocate.clear(); } } }
public class RandomAccessFiles { public static void main(String[] args) throws Exception { RandomAccessFile irandomAccessFile = new RandomAccessFile("111.txt", "r"); RandomAccessFile orandomAccessFile = new RandomAccessFile("copt222.txt", "rw"); FileChannel ichannel = irandomAccessFile.getChannel(); FileChannel ochannel = orandomAccessFile.getChannel(); // long size = ichannel.size(); MappedByteBuffer inMap = ichannel.map(FileChannel.MapMode.READ_ONLY,0,size); MappedByteBuffer outMap = ochannel.map(FileChannel.MapMode.READ_WRITE, 0, size); //4.复制 long start = System.currentTimeMillis(); for (int i = 0; i < size; i++) { byte b = inMap.get(i); outMap.put(i,b); } long end = System.currentTimeMillis(); System.out.println("耗时:" + (end - start)); } }