java 使用NIO进行文件的读写

本文介绍了Java NIO中的FileChannel,讲解了read、write、transferFrom和transferTo等方法的使用,并提供了将数据写入文件和从文件读取数据的示例。重点在于理解FileChannel如何进行文件读写以及零拷贝的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在NIO中使用FileChannel 用于文件数据的读写

FileChannel方法

public int read(ByteBuffer dst)
从通道读取数据并放到缓冲区中,此操作也会移动 Buffer 中的position指针,不断往position中放数据,read完成后position指向limit。
public int write(ByteBuffer src)
把缓冲区的数据写到通道中,此操作也会不断移动Buffer中的position位置直到limit,读取到的数据就是position到limit这两个指针之间的数据。
public long transferFrom(ReadableByteChannel src, long position, long count)
从目标通道中复制数据到当前通道
public long transferTo(long position, long count, WritableByteChannel target)
把数据从当前通道复制给目标通道
该方法拷贝数据使用了零拷贝,通常用来在网络IO传输中,将FileChannel里面的文件数据直接拷贝到与客户端或者服务端连接的Channel里面从而达到文件传输。

将数据写入文件中

package com.boshrong.nio;

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

public class FileChannelTest {
    public static void main(String[] args) throws IOException {
        // 将数据写入到文件中
        String name="bosh_rong 快乐每一天";
        //创建一个输出流
        File file = new File("d:/test.txt");
        FileOutputStream fileOutputStream=new FileOutputStream(file);
        // 获取相应的channel
        FileChannel channel = fileOutputStream.getChannel();
        // 将字符串放入缓存区
        ByteBuffer byteBuffer =ByteBuffer.allocate(1024);
        //将字符串以字节形式放入buffer中
        byteBuffer.put(name.getBytes());
        //开始读取
        byteBuffer.flip();
        //从buffer中读取到文件
        channel.write(byteBuffer);
        fileOutputStream.close();
    }
}

从文件中读取数据

package com.boshrong.nio;

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

public class FileChannelRead {
    public static void main(String[] args) throws IOException {
        // 使用nio从本地读取一个文件
        //File file = new File();
        FileInputStream fileInputStream = new FileInputStream("d:/test.txt");
        // 获取文件相应的channel,channel中会有相关数据
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 将channel的数据读取到buffer
        channel.read(buffer);
        //System.out.println(buffer);
        System.out.println("读取的数据为"+new String(buffer.array()));
        fileInputStream.close();

    }
}

总结

java 输入输出流对象被 NIO FileChannel 所包裹,使用流对象.getChannel() 获取文件对应的channel。channel.write(buffer); 读取buffer的内容到channel,到了channel 也就到了file . channel.read(buffer) 从通道读取数据放入buffer ,从channel读取数据就相当从对应的流对象读取数据。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值