FileChannel通道 NIO 读写

来源:互联网 发布:qq群淘宝优惠券的阴谋 编辑:程序博客网 时间:2024/06/02 20:46
package com.lanou.day21.test;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class TestNIO3 {public static void main(String[] args) throws IOException  {//RandomAccessFile//InputStreamReader//NIO通道/ByteBuffer的使用//使用NIO//先从一个文件读取出来//将内容写入到另一个文件String inputPath=System.getProperty("user.dir")+"/src/com/lanou/day21/test/file.txt";String outPath=System.getProperty("user.dir")+"/src/com/lanou/day21/test/file1.txt";FileInputStream  fi=new FileInputStream(inputPath);FileOutputStream fo=new FileOutputStream(outPath);FileChannel inChannel=fi.getChannel();FileChannel outChannel=fo.getChannel();//创建好管道后首先要做的就是将输入流管道汇总的内容给到bufint length=0;ByteBuffer buf=ByteBuffer.allocate(1024);//用来存储读取到的内容while((length=inChannel.read(buf))!=-1) {//此时buf的文件指针在最后,想要读取其中的内容进行使用需要反转buf.flip();//通过buf往输出管道中写内容outChannel.write(buf);buf.clear();}outChannel.close();inChannel.close();}}