繁体   English   中英

Java按字母顺序将两个文本文件排序为一个文本文件

[英]Java Sort Two Text Files Alphabetically into one Text File

我需要获取两个文本文件,然后按字母顺序将它们排序到一个新创建的文本文件中。

greekWriters.txt包含:

伊索

欧里庇得斯

荷马

柏拉图

苏格拉底

romanWriters.txt包含:

西塞罗

里维

奥维德

维吉尔

这是我的代码:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;


public class Driver {

public static void merge(String name1, String name2, String name3)
{
    File file1 = null, file2 = null, file3 = null;

    Scanner input1 = null, input2 = null;

    PrintWriter output = null;

    try {
        file1 = new File(name1);
        file2 = new File(name2);
        file3 = new File(name3);

        input1 = new Scanner(file1);
        input2 = new Scanner(file2);
        output = new PrintWriter(file3);
        String s1 = input1.nextLine();
        String s2 = input2.nextLine();


     // Problem Area
        while (input1.hasNext() && input2.hasNext())
        {
            if(s1.compareToIgnoreCase(s2) <= 0)
            {
                output.println(s1);
                s1 = input1.nextLine();
            }

            else 
            {
                output.println(s2);
                s2 = input2.nextLine();
            }
        }

    if (s1.compareToIgnoreCase(s2) <= 0)
    {
        output.println(s1 + "\n" + s2);
    }
    else 
    {
        output.println(s2 + "\n" + s1);
    }

    while (input1.hasNext())
    {
        output.println(input1.nextLine());
    }

    while (input2.hasNext())
    {
        output.println(input2.nextLine());
    }
    }

    // problem area end


    catch (IOException e)
    {
        System.out.println("Error in merge()\n" + e.getMessage());
    }

    finally
    {
        if (input1 != null)
        {
            input1.close();
        }
        if (input2 != null)
        {
            input2.close();
        }
        if (output != null)
        {
            output.close();
        }
        System.out.println("Finally block completed.");

    }


}

public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);
    String name1, name2, name3;

    name1 = "greekWriters.txt";

    name2 = "romanWriters.txt";

    System.out.print("Output File: ");
    name3 = input.next();
    merge(name1,name2,name3);
}

}

这是输出:

伊索

西塞罗

欧里庇得斯

荷马

里维

奥维德

柏拉图

维吉尔

苏格拉底

如您所见,这是不按顺序排列的(Virgil和Socrates),我认为问题出在while循环中,当循环正在读取compareToIgnoreCase方法中文本文件的结尾时。 请帮助我找到它不能正确排序的原因,我想今晚睡觉。 谢谢大家的帮助!

刚刚尝试过-


    public static void main(String[] args) {
    try {
      File inputfile1 = new File("C:/_mystuff/test.txt");
      File inputfile2 = new File("C:/_mystuff/test2.txt");

      Scanner readerL = new Scanner(inputfile1);
      Scanner readerR = new Scanner(inputfile2);

      String line1 = readerL.nextLine();
      String line2 = readerR.nextLine();
      while (line1 != null || line2 != null) {
        if (line1 == null) {
          System.out.println("from file2 >> " + line2);
          line2 = readLine(readerR);
        } else if (line2 == null) {
          System.out.println("from file1 >> " + line1);
          line1 = readLine(readerL);
        } else if (line1.compareToIgnoreCase(line2) <= 0) {
          System.out.println("from file1 >> " + line1);
          line1 = readLine(readerL);
        } else {
          System.out.println("from file2 >> " + line2);
          line2 = readLine(readerR);
        }
      }
      readerL.close();
      readerR.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }

  public static String readLine(Scanner reader) {
    if (reader.hasNextLine())
      return reader.nextLine();
    else
      return null;
  }

输入:

文件1:

APPLES
CELERY
DONKEY
ZEBRA

档案2:

BANANA
FRUIT
NINJA
ORANGE
WASHINGTON
xmas
YATCH

输出:

from file1 >> APPLES
from file2 >> BANANA
from file1 >> CELERY
from file1 >> DONKEY
from file2 >> FRUIT
from file2 >> NINJA
from file2 >> ORANGE
from file2 >> WASHINGTON
from file2 >> xmas
from file2 >> YATCH
from file1 >> ZEBRA

我认为这是问题所在:当您退出

while (input1.hasNext() && input2.hasNext())

循环,s1 =“柏拉图”,s2 =“维吉尔”。 然后,继续进行s1和s2的测试并运行:

if (s1.compareToIgnoreCase(s2) <= 0) { output.println(s1 + "\\n" + s2); }

但是问题在于file1中仍然存在少于Virgil的令牌(即“苏格拉底”)。 您不能假设如果s1 <s2在这里您可以立即输出s2。 s1中可能有很多名称小于s2-您必须不断循环遍历s1,直到找到第一个标记> = s2。

这是一个简短的解决方案:

//read in both files
List<String> firstFileLines=Files.readAllLines(file1.toPath(),Charset.  defaultCharset());
List<String> secondFileLines=Files.readAllLines(file2.toPath(),Charset.     defaultCharset());

//put the lines of the two files together
ArrayList<String> allLines=new ArrayList<String>();
allLines.addAll(firstFileLines);
allLines.addAll(secondFileLines);

//sort (case insensitive & write out result
Collections.sort(allLines,String.CASE_INSENSITIVE_ORDER);
File.writeAllLines(outFile.toPath(),allLines,Charset.defaultCharset());

我提供了此解决方案,而不是看到您的问题出在哪里,因为它可以更通用(易于扩展以处理N文件或未排序的文件),并且有时更简单的解决方案比更快的解决方案更好。 请不要冒犯,请根据需要忽略此“答案”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM