java数据通道,Java NIO系列教程(五) 通道之间的数据传输

Java NIO系列教程(五) 通道之间的数据传输

在 Java NIO 中,若是两个通道中有一个是 FileChannel,那你能够直接将数据从一个 channel(译者注:channel 中文常译做通道)传输到另一个 channel。java

1、通道的基本操做

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();

}

2、直接缓冲区拷贝文件

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);

3、transferFrom() 和 transferTo()

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 中。并发

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值