Demo
package cn.itcast.demo05.nio;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;/*NIO里面基于通道和缓冲区*/public class Demo02 {public static void main(String[] args) throws IOException {//创建一个字节输出流FileOutputStream fos = new FileOutputStream("file10.txt");//通过这个流,获取一个通道FileChannel channel = fos.getChannel();//static ByteBuffer allocate(int capacity) 获取一个缓冲区ByteBuffer buff = ByteBuffer.allocate(1024);buff.put("你好".getBytes());buff.flip();//类似于刷新,进行写入前的准备。channel.write(buff);fos.close();}}
Demo
package cn.itcast.demo05.nio;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Demo03 {
public static void main(String[] args) throws IOException {
//创建字节输入流对象
FileInputStream fis = new FileInputStream("file10.txt");
//获取通道
FileChannel channel = fis.getChannel();
//获取缓冲区
ByteBuffer byteArr = ByteBuffer.allocate(1024);
//开始读取,把数据读取到缓冲区
int len = channel.read(byteArr);
//把缓冲区中的数据转成byte数组。
byte[] bArr = byteArr.array();//把这个缓冲区里面的东西转成byte数组
System.out.print(new String(bArr, 0, len));
fis.close();
}
}
