我正在尝试开发一个多线程 java 程序,用于将大文本文件拆分为较小的文本文件。创建的较小文件必须具有前缀行数。例如:如果输入文件的行数是100,输入数是10,我的程序的结果是把输入文件分成10个文件。我已经开发了我的程序的单线程版本:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class TextFileSingleThreaded {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Invalid Input!");
}
//first argument is the file path
File file = new File(args[0]);
//second argument is the number of lines per chunk
//In particular the smaller files will have numLinesPerChunk lines
int numLinesPerChunk = Integer.parseInt(args[1]);
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
long start = System.currentTimeMillis();
try {
line = reader.readLine();
for (int i = 1; line != null; i++) {
writer = new PrintWriter(new FileWriter(args[0] + "_part" + i + ".txt"));
for (int j = 0; j < numLinesPerChunk && line != null; j++) {
writer.println(line);
line = reader.readLine();
}
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
writer.close();
long end = System.currentTimeMillis();
System.out.println("Taken time[sec]:");
System.out.println((end - start) / 1000);
}
}
我想编写这个程序的多线程版本,但我不知道如何读取从指定行开始的文件。请帮帮我。:(