Java多线程读写文件是一个常见的问题,可以通过多线程读写文件来提高文件操作的效率。一般情况下,可以将文件进行分块,每一个线程读取文件的一部分,并将数据写入到另一个文件中。
java
import java.io.*;
public class MultiThreadFileReadWrite {
private static final int THREAD_NUM = 4; // 线程数
private static final int BLOCK_SIZE = 1024 * 1024; // 每个块的大小
public static void main(String[] args) {
String srcPath = "D:/test.txt";
String destPath = "E:/test.txt";
File srcFile = new File(srcPath);
File destFile = new File(destPath);
long fileSize = srcFile.length();
int blockNum = (int) Math.ceil(fileSize * 1.0 / BLOCK_SIZE); // 文件块数
for (int i = 0; i < blockNum; i++) {
long startIndex = i * BLOCK_SIZE;
long endIndex = (i == blockNum - 1) ? (fileSize - 1) : ((i + 1) * BLOCK_SIZE - 1); // 最后一块可能不足BLOCK_SIZE
new Thread(new FileReadWriteThread(srcFile, destFile, startIndex, endIndex)).start();
}
}
}
class FileReadWriteThread implements Runnable {
private File srcFile;
private File destFile;
private long startIndex;
private long endIndex;
public FileReadWriteThread(File srcFile, File destFile, long startIndex, long endIndex) {
this.srcFile = srcFile;
this.destFile = destFile;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public void run() {
byte[] buffer = new byte[1024];
try (RandomAccessFile rafSrc = new RandomAccessFile(srcFile, "r");
RandomAccessFile rafDest = new RandomAccessFile(destFile, "rw")) {
rafSrc.seek(startIndex);
rafDest.seek(startIndex);
int count;
while ((count = rafSrc.read(buffer, 0, (int) Math.min(buffer.length, (endIndex - startIndex + 1)))) != -1) {
rafDest.write(buffer, 0, count);
startIndex += count;
if (startIndex > endIndex) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码使用了RandomAccessFile进行文件的读写操作,用Math.ceil()进行文件块数量的计算,将文件分块后多个线程并发读写文件。在线程内部,使用循环按照文件块大小循环读取和写入文件数据。
需要注意的是,文件的读写操作需要关闭文件流,因此在try-with-resources结构中进行文件流的创建和关闭操作。同时需要加入异常处理机制,保证程序不会因为文件操作异常而中断。