MST
星途 面试题库

面试题:Java中使用NIO进行文件读取与写入的基本步骤

在Java中,如何使用NIO(New I/O)来实现高效的文件读取与写入?请描述主要的步骤,并给出一个简单的示例代码,展示从文件读取内容并写入到另一个文件。
43.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 主要步骤
    • 打开通道:使用FileInputStreamFileOutputStream获取对应的FileChannel,对于读取使用FileInputStream关联的通道,对于写入使用FileOutputStream关联的通道。
    • 分配缓冲区:使用ByteBufferallocate方法分配合适大小的缓冲区。
    • 读取数据到缓冲区:从通道中读取数据到缓冲区,调用FileChannelread方法。
    • 切换缓冲区模式:将缓冲区从写模式切换到读模式,调用ByteBufferflip方法。
    • 将缓冲区数据写入通道:把缓冲区的数据写入目标通道,调用FileChannelwrite方法。
    • 关闭通道:操作完成后关闭FileChannel
  2. 示例代码
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileCopy {
    public static void main(String[] args) {
        String sourceFilePath = "source.txt";
        String targetFilePath = "target.txt";

        try (FileInputStream fileInputStream = new FileInputStream(sourceFilePath);
             FileOutputStream fileOutputStream = new FileOutputStream(targetFilePath);
             FileChannel inputChannel = fileInputStream.getChannel();
             FileChannel outputChannel = fileOutputStream.getChannel()) {

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (inputChannel.read(buffer) != -1) {
                buffer.flip();
                outputChannel.write(buffer);
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码从source.txt文件读取内容,并将其写入到target.txt文件。通过FileChannelByteBuffer实现了NIO的文件读写操作。