读取超级大的文件 java 去读写的方式
时间: 2024-02-04 21:17:00 浏览: 22
您好!对于超大的文件,为了避免一次性将整个文件读入内存导致内存溢出,一般采用分块读取的方式进行处理。以下是一个基于Java NIO的示例代码,可以实现分块读取大文件,并将读取到的内容写入到新文件中:
```java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadLargeFile {
public static void main(String[] args) throws IOException {
String sourceFilePath = "path/to/large/file.txt";
String destFilePath = "path/to/new/file.txt";
int bufferSize = 1024 * 1024; // 缓冲区大小,这里设置为1MB
try (RandomAccessFile sourceFile = new RandomAccessFile(sourceFilePath, "r");
FileChannel sourceChannel = sourceFile.getChannel();
RandomAccessFile destFile = new RandomAccessFile(destFilePath, "rw");
FileChannel destChannel = destFile.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
while (sourceChannel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
destChannel.write(buffer);
}
buffer.clear();
}
}
}
}
```
在上述代码中,我们先创建RandomAccessFile和FileChannel对象,分别表示要读取的大文件和写入的新文件。然后,定义一个缓冲区,大小为1MB。在while循环中,每次从源文件通道中读取一块数据(大小为缓冲区大小),并将读取到的数据写入到目标文件通道中。最后,记得在try-with-resources语句中关闭相关资源。
希望能帮到您!