我将一个 10 GB 的文件拆分为 100000 + 几百个单词的多个文件(因为当我遇到 100000 个单词时我读到了一行)。
private void splitInputFile(String path) {
try{
File file=new File(path);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String temp;
temp = br.readLine();
String fileName="fileName";
int fileCount = 1;
while(temp!=null){
//TODO Read 100000 words, sort and write to a file. Repeat for the entire file
if(wordsToBeSorted.size()<=100000){
startCounting(temp);
temp=br.readLine();
}//end of if -> place 100000+ words inside the list
else{
Collections.sort(wordsToBeSorted);
fileName = "fileName"+fileCount;
fileCount++;
File splitFile = new File(fileName);
PrintWriter pr = new PrintWriter(splitFile);
for(String word:wordsToBeSorted){
pr.write(word);
pr.write("\n");//check if this works -> 1 word per line
}//end of for
}//end of else
}//end of while
mergeSort(fileCount);
}//end of try
catch(Exception e){
e.printStackTrace();
}
}
private void startCounting(String sb) {
StringTokenizer tokenizer = new StringTokenizer(sb);// Split by space
while (tokenizer.hasMoreTokens()) {
String text = tokenizer.nextToken();
text = text.replaceAll("\\W", "");// Remove all symbols
if("".equals(text.trim()))
continue;
wordsToBeSorted.add(text);
}
}
现在我想知道如何对这些文件进行排序。我发现我应该做一个合并排序。考虑到每个 splitFile 的字数可变(100000 + 几个额外的字)的事实,是否可以进行涉及可变字数文件的合并排序?还是我应该遵循其他方法来拆分文件?