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

来源:互联网 发布:办公软件速成班北京 编辑:程序博客网 时间:2024/05/21 06:54

在Java NIO中,如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel(译者注:channel中文常译作通道)传输到另外一个channel。

transferFrom()

FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中(译者注:这个方法在JDK文档中的解释为将字节从给定的可读取字节通道传输到此通道的文件中)。下面是一个简单的例子:

package mymina;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.channels.FileChannel;public class FileChannel1 {public static void main(String[] args) throws IOException {    String fromfilename = System.getProperty("user.dir")+"\\src\\mymina\\fromFile.txt";      System.out.println("logfile.path:"+fromfilename);            RandomAccessFile fromFile = new RandomAccessFile(fromfilename,"rw");FileChannel fromChannel = fromFile.getChannel();String tofilename = System.getProperty("user.dir")+"\\src\\mymina\\toFile.txt";  System.out.println("logfile.path:"+tofilename);  RandomAccessFile toFile = new RandomAccessFile(tofilename,"rw");FileChannel toChannel = toFile.getChannel();long position = 0;long count = fromChannel.size();System.out.println(count);//toChannel.transferFrom(fromChannel, count,position);//fromChannel.transferTo(position, count, toChannel);toChannel.transferFrom(fromChannel, position, count);}

方法的输入参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。
此外要注意,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。

transferTo()

transferTo()方法将数据从FileChannel传输到其他的channel中。下面是一个简单的例子:

fromChannel.transferTo(position, count, toChannel);

是不是发现这个例子和前面那个例子特别相似?除了调用方法的FileChannel对象不一样外,其他的都一样。
上面所说的关于SocketChannel的问题在transferTo()方法中同样存在。SocketChannel会一直传输数据直到目标buffer被填满。

注意:

JDK中关于FileChannel的实现,是rt.jar里的FileChannelImpl类。对于FileChannel之间的transferFrom,第三个参数count会有限制,最大值是int的MAX_VALUE,就是说一次性传输的最多2147483647个字节,所以你的文件超过了2.1G(左右),FileChannel就会自动给你截断了,这个是JDK底层实现的限制。

1 0
原创粉丝点击