在 Java NIO 中,若是两个通道中有一个是 FileChannel,那你能够直接将数据从一个 channel(译者注:channel 中文常译做通道)传输到另一个 channel。java
FileInputStream fis = new FileInputStream("1.png"); FileOutputStream fos = new FileOutputStream("2.png"); //1. 获取通道 FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); //2. 分配缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024); //3. 用通道传输数据 while (inChannel.read(buf) != -1) { buf.flip(); outChannel.write(buf); buf.clear(); }
FileChannel inChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("3.png"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); //内存映射文件,直接缓冲区 MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size()); byte[] bytes = new byte[inMappedBuf.limit()]; inMappedBuf.get(bytes); outMappedBuf.put(bytes);
FileChannel 的 transferFrom() 方法能够将数据从源通道传输到 FileChannel 中(译者注:这个方法在 JDK 文档中的解释为将字节从给定的可读取字节通道传输到此通道的文件中)。下面是一个简单的例子:编程
RandomAccessFile inFile = new RandomAccessFile("fromFile.txt", "rw"); FileChannel inChannel = fromFile.getChannel(); RandomAccessFile outFile = new RandomAccessFile("toFile.txt", "rw"); FileChannel outChannel = toFile.getChannel(); long position = 0; long count = inChannel.size(); outChannel.transferFrom(position, count, inChannel); //inChannel.transferTo(position, count, outChannel);
方法的输入参数 position 表示从 position 处开始向目标文件写入数据,count 表示最多传输的字节数。若是源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。
此外要注意,在 SoketChannel 的实现中,SocketChannel 只会传输此刻准备好的数据(可能不足 count 字节)。所以,SocketChannel 可能不会将请求的全部数据(count 个字节)所有传输到 FileChannel 中。并发
转载自并发编程网 – ifeve.com,本文连接地址: Java NIO系列教程(二) Channelapp