我有2个文本文件,其中包含按升序排序的数字(整数)。现在我想创建一个包含两个文件中所有数字的新文本文件。换句话说,必须将两个文件中的值合并为一个新文件。新文件中的数字也必须按升序排列。
例如:
file1:1 3 5 7 9
file2:2 4 6 8 10
新文件必须包含:1 2 3 4 5 6 7 8 9 10
在我创建的方法中,问题是它开始扫描两个文件中的第一个数字file1:1 file2:2。它发现file1中的数字是扫描程序进入下一个文件的最小数字两个文件中的数字。所以正在扫描的下一件事是file1:3 file2:4然后它是3,这是最少的。但是,已跳过第一次扫描的数字2和第二次扫描的数字4。到目前为止,这是我的代码:
public static void mergeAllNumbers(String fileName1, String fileName2, String fileNameNew)
throws FileNotFoundException {
Scanner scanFile1 = new Scanner(new File(fileName1));
Scanner scanFile2 = new Scanner(new File(fileName2));
PrintWriter writeToFile = new PrintWriter(fileNameNew);
// merge as long as there is something in both files
while (scanFile1.hasNextInt() && scanFile2.hasNextInt()) {
int value1 = scanFile1.nextInt();
int value2 = scanFile2.nextInt();
if (value1 <= value2) {
// The number in fileName1 is less
writeToFile.write(value1 + "");
writeToFile.write(System.getProperty("line.separator"));
} else { // The number in fileName2 is less
writeToFile.write(value2 + "");
writeToFile.write(System.getProperty("line.separator"));
}
}
// empty the file which is not empty
while (scanFile1.hasNextInt()) {
int value1 = scanFile1.nextInt();
writeToFile.write(value1 + "");
writeToFile.write(System.getProperty("line.separator"));
}
while (scanFile2.hasNextInt()) {
int value2 = scanFile2.nextInt();
writeToFile.write(value2 + "");
writeToFile.write(System.getProperty("line.separator"));
}
scanFile1.close();
scanFile2.close();
writeToFile.close();
}
答案 0 :(得分:1)
我看到你失踪的东西:
1)在您第一次读取这两个文件之后,您只需阅读您正在写入的文件。 (如果你写了file1的值,那么从文件1中读取下一个值。)
2)考虑两个值相等,在这种情况下,您确实写入两个值,并从两个文件中读取下一个值。这是假设合并意味着所有记录合并即使它们是重复的。
while循环应如下所示:
int value1 = -1; // -1 just to give it an initial value
int value2 = -1;
boolean eof1 = !scanFile1.hasNextInt();
booelan eof2 = !scanFile2.hasNextInt();
if(!eof1){
value1 = scanFile1.nextInt();
}
if(!eof2){
value2 = scanFile2.nextInt();
}
while (!eof1 && !eof2) {
if (value1 < value2) {
// The number in fileName1 is less
writeToFile.write(value1 + "");
writeToFile.write(System.getProperty("line.separator"));
eof1 = !scanFile1.hasNextInt();
if(!eof1){
value1 = scanFile1.nextInt();
}
} else if(value1 > value2){ // The number in fileName2 is less
writeToFile.write(value2 + "");
writeToFile.write(System.getProperty("line.separator"));
eof2 = !scanFile2.hasNextInt();
if(!eof2){
value2 = scanFile2.nextInt();
}
}else{ // they are equal
writeToFile.write(value1 + "");
writeToFile.write(System.getProperty("line.separator"));
eof1 = !scanFile1.hasNextInt();
if(!eof1){
value1 = scanFile1.nextInt();
}
eof2 = !scanFile2.hasNextInt();
if(!eof2){
value2 = scanFile2.nextInt();
}
}
}
答案 1 :(得分:0)
由于您在两个文件上调用.nextInt(),因此您将始终丢失您不使用的数字。您可以将两者读入两个单独的数组,然后对它们执行合并排序。 https://www.geeksforgeeks.org/merge-sort/