面试题答案
一键面试- 主要步骤:
- 打开通道:使用
FileInputStream
或FileOutputStream
获取对应的FileChannel
,对于读取使用FileInputStream
关联的通道,对于写入使用FileOutputStream
关联的通道。 - 分配缓冲区:使用
ByteBuffer
的allocate
方法分配合适大小的缓冲区。 - 读取数据到缓冲区:从通道中读取数据到缓冲区,调用
FileChannel
的read
方法。 - 切换缓冲区模式:将缓冲区从写模式切换到读模式,调用
ByteBuffer
的flip
方法。 - 将缓冲区数据写入通道:把缓冲区的数据写入目标通道,调用
FileChannel
的write
方法。 - 关闭通道:操作完成后关闭
FileChannel
。
- 打开通道:使用
- 示例代码:
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
文件。通过FileChannel
和ByteBuffer
实现了NIO的文件读写操作。