NIO例子

public class Main3 {

    /**
     * nio读取文件中的数据
     * @param args
     */
    public static void main(String[] args) throws IOException {
        readThenWrite();
    }


    /**
     * nio读取文件中的数据
     * 文件 -> channel -> buffer
     * @throws IOException
     */
    public static void read() throws IOException{
        // 获取输入流
        FileInputStream fis = new FileInputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\read.txt");
        // 获取通道
        FileChannel readChannel = fis.getChannel();
        // 创建一个1024字节大小的缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        // 从通道读取数据到缓冲区,并返回读取的字节数
        int readBytes = readChannel.read(buf);
        // 读取的字节数不等于-1,说明有数据
        while(readBytes != -1){
            byte[] bs = new byte[readBytes];
            // 由写模式切换为读模式
            buf.flip();
            // 缓冲区还有数据可以读
            while(buf.hasRemaining()){
                buf.get(bs);
                String str = new String(bs, 0, readBytes);
                System.out.println(str);
            }
            // 清空缓冲区数据
            buf.clear();
            // 再次从通道中读取数据到缓冲区,知道没有数据
            readBytes = readChannel.read(buf);
        }
        fis.close();
    }


    /**
     * 写入文件 存在问题,待修改
     * buffer -> channel -> 文件
     * @throws IOException
     */
    public static void write() throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\write.txt");
        FileChannel channel = fos.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.put("2312312312".getBytes(StandardCharsets.UTF_8));
        System.out.println(buf.toString());
        int writeBytes = channel.write(buf);
        fos.close();
    }


    /**
     * 文件复制
     */
    public static void readThenWrite() throws IOException {
        FileInputStream fis = new FileInputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\read.txt");
        FileOutputStream fos = new FileOutputStream("D:\\ideaProject\\helloWorld\\src\\main\\resources\\write.txt");
        FileChannel readChannel = fis.getChannel();
        FileChannel writeChannel = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(readChannel.read(buffer) != -1){
            // 切换为读模式
            buffer.flip();
            writeChannel.write(buffer);
            buffer.clear();
        }
        fis.close();
        fos.close();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值