Netty学习笔记 3.5 应用实例3-使用一个Buffer完成文件读取

应用实例3-使用一个Buffer完成文件读取

实例要求:

使用 FileChannel(通道) 和 方法 read , write,完成文件的拷贝

拷贝一个文本文件 1.txt , 放在项目下即可
代码演示

package com.my.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
        //FileOutputStream
        //该类用来创建一个文件并向文件中写数据。
        //
        //如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。
        //
        //有两个构造方法可以用来创建 FileOutputStream 对象。
        //
        //使用字符串类型的文件名来创建一个输出流对象:
        //
        //OutputStream f = new FileOutputStream("C:/java/hello")
        //
        //也可以使用一个文件对象来创建一个输出流来写文件。我们首先得使用File()方法来创建一个文件对象:
        //
        //File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(f);
        //
        //创建OutputStream 对象完成后,就可以使用下面的方法来写入流或者进行其他的流操作。
        //第二个参数  此构造方法为重载方法 有带一个参数的 如:fos = new FileOutputStream(file)这种, 也有像下面这种带两个参数的, 其实如果不写实际上就是 第二个参数默认为false; 第二个参数表示是否在源文件已有内容的后面进行追加写入新的内容, 即true表示在原有内容的基础上进行追加写入写内容; false表示覆盖擦除原有内容, 写入后只包含新写入内容, 原有内容将会被覆盖不存保留
        //  fos = new FileOutputStream(file,true);
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        //创建通道
        FileChannel fileChannel01 = fileInputStream.getChannel();
        //使用之前,FileChannel必须被打开,但是你无法直接打开FileChannel。
        // 需要通过InputStream,OutputStream或RandomAccessFile获取FileChannel。
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();
        //缓冲区建立
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        //首先:给Buffer分配大小, 从中FileChannel读取的数据会被读入Buffer。
        //
        //其次:调用FileChannel的read()方法。这个方法从FileChannel读取数据读入到Buffer。read()方法返回值是int类型,表示多少个字节被插入Buffer。如果返回-1,则到达文件结尾即文件读取完成。
        //https://www.cnblogs.com/kuoAT/p/7010056.html
        while (true) { //循环读取

            //这里有一个重要的操作,一定不要忘了
            /*
             public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
             */
            //务必清空buffer
            byteBuffer.clear(); //清空buffer
            //读入缓冲区
            int read = fileChannel01.read(byteBuffer);
            System.out.println("read =" + read);
            if(read == -1) { //表示读完
                break;
            }
            //将buffer 中的数据写入到 fileChannel02 -- 2.txt
            byteBuffer.flip();
            //从缓冲区数据写入到文件
            fileChannel02.write(byteBuffer);
        }

        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}

猜你喜欢

转载自blog.csdn.net/zyzy123321/article/details/107592811
3.5
今日推荐