Channels和Buffers是JAVA NIO里面比较重要的两个概念,NIO正是基于Channels和Buffers进行数据操作,且数据总是从Channels读取到Buffers,或者从Buffers写入到Channels。通道(Channel)可以从通道写输入,也可以读数据 ...
Channels和Buffers是JAVA NIO里面比较重要的两个概念,NIO正是基于Channels和Buffers进行数据操作,且数据总是从Channels读取到Buffers,或者从Buffers写入到Channels。
通道(Channel)
- 可以从通道写输入,也可以读数据;
- 通道的数据是跟Buffer进行交互的,数据可以读到Buffer,也可以从Buffer写数据到通道;
- 还可以异步读写数据;
以FileChannel为例,如下:
FileChannel
FileChannel是文件写入/读取相关的通道;
产生FileChannel的方式:
- 从FileOutputStream中获取;
- 从RandomAccessFile中获取;
- 从FileInputStream中获取;
下面举个例子,分别从FileOutputStream、RandomAccessFile、FileInputStream中获取文件通道,进行相关写入/读取操作;
package com.pichen.io;import java.nio.*;import java.nio.channels.*;import java.io.*;public class GetChannel { private static final int BSIZE = 1024; public static void main(String[] args) throws Exception { // 创建文件输出字节流 FileOutputStream fos = new FileOutputStream("data.txt"); //得到文件通道 FileChannel fc = fos.getChannel(); //往通道写入ByteBuffer fc.write(ByteBuffer.wrap("Some text ".getBytes())); //关闭流 fos.close(); //随机访问文件 RandomAccessFile raf = new RandomAccessFile("data.txt", "rw"); //得到文件通道 fc = raf.getChannel(); //设置通道的文件位置 为末尾 fc.position(fc.size()); //往通道写入ByteBuffer fc.write(ByteBuffer.wrap("Some more".getBytes())); //关闭 raf.close(); //创建文件输入流 FileInputStream fs = new FileInputStream("data.txt"); //得到文件通道 fc = fs.getChannel(); //分配ByteBuffer空间大小 ByteBuffer buff = ByteBuffer.allocate(BSIZE); //从通道中读取ByteBuffer fc.read(buff); //调用此方法为一系列通道写入或相对获取 操作做好准备 buff.flip(); //从ByteBuffer从依次读取字节并打印 while (buff.hasRemaining()){ System.out.print((char) buff.get()); } fs.close(); }}
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:【JAVA NIO】Channels和Buffers
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。