Netty学习笔记 3.3 应用实例1-本地文件写数据

应用实例1-本地文件写数据

实例要求:

使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道), 将 “hello,netty” 写入到file01.txt 中

文件不存在就创建
代码演示

package com.my.nio;

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

public class NIOFileChannel01 {
    public static void main(String[] args) throws Exception{

        String str = "hello,netty";
        //创建一个输出流->channel
        //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);
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");

        //通过 fileOutputStream 获取 对应的 FileChannel
        //这个 fileChannel 真实 类型是  FileChannelImpl
        //FileChannel:用于读取、写入、映射和操作文件的通道
        //创建一个filechannel
        FileChannel fileChannel = fileOutputStream.getChannel();

        //创建一个缓冲区 ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        //将 str 放入 byteBuffer
        byteBuffer.put(str.getBytes());


        //对byteBuffer 进行flip
        byteBuffer.flip();

        //将byteBuffer 数据写入到 fileChannel
        fileChannel.write(byteBuffer);
        //关闭流
        fileOutputStream.close();

    }
}

猜你喜欢

转载自blog.csdn.net/zyzy123321/article/details/107592678
3.3
今日推荐