FileChannel应用实例——使用一个Buffer完成文件的读取、写入

package com.atguigu.nio;

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

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

        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) { //循环读取

            //这里有一个重要的操作,一定不要忘了
            /*
             public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
             */
            byteBuffer.clear(); //清空buffer
            int read = fileChannel01.read(byteBuffer);
            System.out.println("read =" + read);
            if(read == -1) { //表示读完
                break;
            }
            //将buffer 中的数据写入到 fileChannel02 -- 2.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }

        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个文件分块写入一个文件中,您可以使用FileChannel和MappedByteBuffer来实现。以下是一个示例代码片段,演示了如何将大文件分块写入文件中: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class FileChunkWriteExample { public static void main(String[] args) { String sourceFilePath = "path/to/source/file"; String destinationFilePath = "path/to/destination/file"; int bufferSize = 1024 * 1024; // 每个缓冲区的大小(1MB) try (FileChannel sourceChannel = new FileInputStream(sourceFilePath).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFilePath).getChannel()) { long fileSize = sourceChannel.size(); long position = 0; long remaining = fileSize; while (remaining > 0) { long chunkSize = Math.min(bufferSize, remaining); MappedByteBuffer buffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, position, chunkSize); destinationChannel.write(buffer); position += chunkSize; remaining -= chunkSize; } System.out.println("文件分块写入成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 请确保将示例代码中的"sourceFilePath"和"destinationFilePath"替换为实际的文件路径。在这个示例中,我们使用一个1MB的缓冲区来分块读取文件,并将每个缓冲区的数据写入目标文件中。您可以根据需要调整缓冲区的大小。 请注意,此示例代码没有处理异常情况,您可能需要进行适当的异常处理和错误检查。另外,如果目标文件已经存在,这段代码会覆盖目标文件的内容。如果您想追加数据而不是覆盖,请使用FileOutputStream的构造函数中传递第二个参数为`true`来打开文件输出流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值