美文网首页
netty网络编程-2.NIOFile

netty网络编程-2.NIOFile

作者: 笨鸡 | 来源:发表于2020-03-30 21:17 被阅读0次
package com.ctgu.nio.file;


import org.junit.Test;

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

public class TestNIO {

    private final String PATH = new File("").getCanonicalPath();

    public TestNIO() throws IOException {
    }

    @Test
    public void write() throws Exception{
        // 1.创建输出流
        FileOutputStream fos = new FileOutputStream(PATH + "basic.txt");
        // 2.从流中得到一个通道
        FileChannel fc = fos.getChannel();
        // 3.提供一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4.往缓冲区存数据
        String str = "hello.nio";
        buffer.put(str.getBytes());
        // 5.buffer反转
        buffer.flip();
        // 6.把缓冲区写入到通道
        fc.write(buffer);
        // 7.关闭
        fos.close();
    }

    @Test
    public void read() throws Exception{
        File file = new File(PATH + "basic.txt");
        // 1.创建输入流
        FileInputStream fis = new FileInputStream(file);
        // 2.从流中得到一个通道
        FileChannel fc = fis.getChannel();
        // 3.提供一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
        // 4.往缓冲区读数据
        fc.read(buffer);
        System.out.println(new String(buffer.array()));
        // 5.关闭
        fis.close();
    }

    @Test
    public void copy() throws Exception{
        // 1.创建输入输出流
        FileInputStream fis = new FileInputStream(PATH + "basic.txt");
        FileOutputStream fos = new FileOutputStream(PATH + "copy.txt");
        // 2.从流中得到一个通道
        FileChannel sourceFC = fis.getChannel();
        FileChannel  descFC= fos.getChannel();
        // 3.提供一个缓冲区
        descFC.transferFrom(sourceFC, 0, sourceFC.size());
//        sourceFC.transferTo(0, sourceFC.size(), descFC);
        // 4.关闭
        fis.close();
        fos.close();
    }
}

相关文章

网友评论

      本文标题:netty网络编程-2.NIOFile

      本文链接:https://www.haomeiwen.com/subject/azybuhtx.html