Java NIO 通道和通道之间转换
2014-12-30 15:26
447 查看
在Java NIO中你可以将数据从一个通道直接转移到另一个通道,如果其中一个通道是FileChannel。在FileChannel类中有transferTo()和transferFrom()方法来实现这种转移。
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(fromChannel, position, count);
参数position用来指定写入目标文件数据的起始位置,count用来指定向目标文件写入多少字节的数据。如果源通道中不足count个字节,则有多少转移多少。
另外,一些SocketChannel也可以实现数据转移,只要它内置的缓冲区已经有数据,不管它后续还是否有数据达到。因此,可能不能讲将请求的全部数据从SocketChannel转移到FileChannel。
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel);
这个例子和上一个例子类似。唯一的不同时调用不同的FileChannel对象,其它都一样。
上面我们的提到的关于SocketChannel的问题在使用transferTo()方法时任然存在。
transferFrom()
FileChannel.transferFrom()方法可以将数据从一个通道转移到一个特定的FileChannnel。下面是一个简单的示例:RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(fromChannel, position, count);
参数position用来指定写入目标文件数据的起始位置,count用来指定向目标文件写入多少字节的数据。如果源通道中不足count个字节,则有多少转移多少。
另外,一些SocketChannel也可以实现数据转移,只要它内置的缓冲区已经有数据,不管它后续还是否有数据达到。因此,可能不能讲将请求的全部数据从SocketChannel转移到FileChannel。
transferTo()
transferTo()方法将一个FileChannel的数据转移到其它的一些通道。下面是一个简单的示例:RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel);
这个例子和上一个例子类似。唯一的不同时调用不同的FileChannel对象,其它都一样。
上面我们的提到的关于SocketChannel的问题在使用transferTo()方法时任然存在。
相关文章推荐
- Java基础知识强化之IO流笔记76:NIO之 Channel(通道)之间的数据传输
- Java NIO 通道之间的数据传输
- Java NIO深入理解通道之间数据传输
- AXIS2中OMElement和Java对象之间的转换
- 利用XStream在Java对象和XML之间相互转换
- java.util.Date 和 java.sql.Date 之间的转换
- JAVA基本数据类型与其他语言数据类型之间的转换方法
- Java 基本数据类型和Sting之间的相互转换
- 用Apache Commons Betwixt2 在XML与Java对象之间相互转换
- Java 数据类型 和 与String之间的转换
- Java的十六进制与字符串之间互相转换函数(16进制与String转换)
- 常见Java 中数据类型之间的转换的方法!
- java中String,Integer,int之间转换
- 常见Java 中数据类型之间的转换的方法!
- java基本数据类型之间的转换
- Java中几种常用数据类型之间转换的方法
- JAVA基本数据类型与其他语言数据类型之间的转换方法
- Java 中数据类型之间的转换
- JAVA里面关于byte数组和String之间的转换问题
- 常见Java 中数据类型之间的转换的方法!