NIO之文件IO

本文详细介绍使用Java进行文件读写的基本操作,包括向本地文件写入数据、从本地文件读取数据,以及如何将一个文件的数据复制到另一个文件。通过具体示例代码,展示如何利用FileInputStream、FileOutputStream、FileChannel和ByteBuffer等类实现文件操作。

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

public class TestFile {

    // 向本地文件写入数据
    @Test
    public void testWriteFile() throws Exception {
        // 1. 创建输出流
        FileOutputStream fos = new FileOutputStream("basic.txt");
        // 2. 基于输出流创建通道
        FileChannel fc = fos.getChannel();
        // 3. 获取缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4. 将数据放入缓冲区, 此时指针指向最后一个字符的下一位。
        buffer.put("hello nio".getBytes());
        // 5. 将指针指向开头,不做此操作,数据将从指针位置往下读取。
        // 	  也就是说不做此操作读到的都是空白。
        buffer.flip();
        // 发送
        fc.write(buffer);
        // 关闭流
        fos.close();
    }

    // 从本地文件获取数据
    @Test
    public void testReadFile() throws Exception {
        File file = new File("basic.txt");
        // 1. 创建输入流
        FileInputStream fis = new FileInputStream(file);
        // 2. 获取channel
        FileChannel fc = fis.getChannel();
        // 3. 获取buffer
        ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
        // 4. 获取数据
        fc.read(buffer);
        System.out.println(new String(buffer.array()));
    }

    // 将一个文件数据复制到另一个文件
    @Test
    public void testCopyFile() throws Exception {
        File file = new File("basic.txt");
        // 1. 创建输入流 输出流
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream("copyBasic.txt");
        // 2. 获取输入输出channel
        FileChannel readChannel = fis.getChannel();
        FileChannel writeChannel = fos.getChannel();
        // 3. copy数据
        readChannel.transferTo(0, readChannel.size(), writeChannel);
        // writeChannel.transferFrom(readChannel, 0, readChannel.size());
        // 6. 关闭数据
        fis.close();
        fos.close();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值