簡體   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