Netty学习之通道Channel和缓冲区Buffer
package com.huangz.demo.nio; import io.netty.buffer.ByteBuf; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * 利用FileChannel通道和Buffer缓存区向本地磁盘写一个文件 */ public class NIOFileChannel { public static void main(String[] args) throws Exception { //向本地文件写数据 //writeFile(); //从本地文件读数据 //readFile(); //文件复制 copyFile(); } /** * 用FileChannel通道和Buffer缓冲区向本地文件写数据 */ private static void writeFile() throws Exception{ //创建一个输出流 FileOutputStream fileOutputStream = new FileOutputStream("d:\file01.txt"); //通过文件输出流,获取对应的通道 FileChannel fileChannel = fileOutputStream.getChannel(); //创建一个缓冲区 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); String str ="Netty必知必会"; byteBuffer.put(str.getBytes()); //flip前:position= 17,limit=1024 //从写转换为读,flip反转,这一步发生了什么? position和limit值的变化 byteBuffer.flip(); //flip后:position= 0,limit=17 //将缓冲区数据写入到通道 fileChannel.write(byteBuffer); //关闭流 fileOutputStream.close(); System.out.println("写入文件完成..."); } /** * 用FileChannel通道和Buffer缓冲区从本地文件读数据 */ private static void readFile() throws Exception { System.out.println("开始读取数据...."); //创建文件的输入流 File file = new File ("D:\file01.txt"); FileInputStream fileInputStream = new FileInputStream(file); //获取通道 FileChannel fileChannel = fileInputStream.getChannel(); //创建缓冲区 int length = (int)file.length(); ByteBuffer byteBuffer = ByteBuffer.allocate(length); //将读取通道数据到缓冲区 fileChannel.read(byteBuffer); //从缓冲区中取数据 byte[] bytes = byteBuffer.array(); fileInputStream.close(); System.out.println(new String(bytes)); } /** * 文件拷贝 * @throws Exception */ private static void copyFile() throws Exception { //读文件 创建输入流 FileInputStream fileInputStream = new FileInputStream("1.txt"); FileChannel channel01 = fileInputStream.getChannel(); //写文件 创建输出流 FileOutputStream fileOutputStream = new FileOutputStream("2.txt"); FileChannel channel02 = fileOutputStream.getChannel(); //创建一个Buffer ByteBuffer byteBuffer =ByteBuffer.allocate(10); while (true){ //从通道读取数据 byteBuffer.clear(); int read = channel01.read(byteBuffer); if(read==-1){ break; } //读写转换 byteBuffer.flip(); //将读取到的数据,写入到2.txt channel02.write(byteBuffer); } fileInputStream.close(); fileOutputStream.close(); System.out.println("复制文件完成"); } }