与Java的常规IO API相比,Java NIO是一种针对数据IO操作进行了更优化处理的新API,Java NIO提供从多个缓冲区读取数据或向多个缓冲区写入数据或将数据写入通道的功能。
为了实现从通道的多次读写,Java NIO提供了ScatteringByteChannel和GatheringByteChannel API,如以下示例所示。
为了从多个通道读取数据,无涯教程需要将数据从单个通道读取到多个缓冲区中, 使用ScatteringByteChannel read()方法从通道中将数据读取存入数组中,当缓冲区已存满,通道将自动继续填充下一个缓冲区。
以下示例显示了如何在Java NIO中执行数据分散
C:/Test/temp.txt
Hello World!
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ScatteringByteChannel; public class ScatterExample { private static String FILENAME="C:/Test/temp.txt"; public static void main(String[] args) { ByteBuffer bLen1=ByteBuffer.allocate(1024); ByteBuffer bLen2=ByteBuffer.allocate(1024); FileInputStream in; try { in=new FileInputStream(FILENAME); ScatteringByteChannel scatter=in.getChannel(); scatter.read(new ByteBuffer[] {bLen1, bLen2}); bLen1.position(0); bLen2.position(0); int len1=bLen1.asIntBuffer().get(); int len2=bLen2.asIntBuffer().get(); System.out.println("Scattering : Len1=" + len1); System.out.println("Scattering : Len2=" + len2); } catch (FileNotFoundException exObj) { exObj.printStackTrace(); } catch (IOException ioObj) { ioObj.printStackTrace(); } } }
运行上面代码输出
Scattering : Len1=1214606444 Scattering : Len2=0
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)