目录
Java NIO(New I/O)是 Java 1.4 引入的一组提供更强大、更灵活的 I/O 操作的 API。它主要包括 java.nio
包,其中的核心组件是 java.nio.channels
和 java.nio.file
。
一、FileChannel
FileChannel
是 Java NIO 中用于读取和写入文件的通道。它是 java.nio.channels
包中的一个接口,提供了一些方法,使得对文件进行读写变得更为灵活。以下是一些 FileChannel
的常用操作:
1. 打开 FileChannel
你可以使用 RandomAccessFile
或者 FileInputStream
/ FileOutputStream
来获取一个 FileChannel
对象。
使用 RandomAccessFile
:
RandomAccessFile file = new RandomAccessFile("example.txt", "rw");
FileChannel channel = file.getChannel();
使用 FileInputStream
和 FileOutputStream
:
FileInputStream fis = new FileInputStream("example.txt");
FileChannel inputChannel = fis.getChannel();
FileOutputStream fos = new FileOutputStream("output.txt");
FileChannel outputChannel = fos.getChannel();
2. 读取数据到 ByteBuffer
使用 read()
方法可以将数据从 FileChannel
读取到 ByteBuffer
中。
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
3. 写入数据到 FileChannel
使用 write()
方法可以将数据从 ByteBuffer
写入到 FileChannel
。
ByteBuffer buffer = ByteBuffer.wrap("Hello, World!".getBytes());
int bytesWritten = channel.write(buffer);
4. 文件位置操作
FileChannel
维护一个当前位置(position),读写操作都是从当前位置开始的。在读写之后,位置会自动更新。
long currentPosition = channel.position(); // 获取当前位置
channel.position(newPosition); // 设置新的位置
channel.position(channel.size()); // 将位置设置到文件末尾
5. 文件截取
truncate()
方法可以截取文件的长度。截取文件后,文件的大小将被截短,多余的部分被删除。
channel.truncate(newSize);
6. 强制刷新
force()
方法可以强制将文件的所有修改写入磁盘。
channel.force(true); // 强制将文件的所有修改写入磁盘
7. 关闭 FileChannel
使用 close()
方法关闭 FileChannel
。
channel.close();
二、FileChannel
读取文件内容
使用FileChannel读取文件内容
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelExample {
public static void main(String[] args) {
try {
// 打开文件通道
RandomAccessFile file = new RandomAccessFile("example.txt", "r");
FileChannel channel = file.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 从通道读取数据到缓冲区
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead + " bytes.");
// 切换缓冲区为读模式
buffer.flip();
// 读取缓冲区中的数据
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
// 清空缓冲区
buffer.clear();
// 继续从通道读取数据到缓冲区
bytesRead = channel.read(buffer);
}
// 关闭通道和文件
channel.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个示例打开一个文件通道,然后使用 ByteBuffer
缓冲区从文件中读取数据。读取后,缓冲区切换为读模式,然后逐个字节输出。