簡體   English   中英

如何按字母順序對文本文件進行排序?

[英]How do I sort a text file alphabetically?

例如,我想要以下數據:

     Manufacturer : - Violin

     Type : - Electric

     Colour: - Blue

     Price : $23



     Manufacturer : - Guitar

     Type : - Electric

     Colour: - Red

     Price : $54

看起來像:

     Manufacturer : - Guitar

     Type : - Electric

     Colour: - Red

     Price : $54



     Manufacturer : - Violin

     Type : - Electric

     Colour: - Blue

     Price : $23

(請注意,小提琴信息在吉他下方是如何排列的,因為按字母順序位於“ G”吉他之后。)

解決此問題的完整代碼將需要較長的時間才能得到答復,但我可以為您提供一些指導:

首先創建一個類,其中包含有關每個對象“ Violin”,“ Guitar”等的信息。基本上,該類如下所示:

public class BlockOfText
{
   public String name;

   public String block;
}

,其中“名稱”是“吉他”和“小提琴”,“塊”是整個塊。 現在,從輸入文件中讀取每個塊,並將它們保存在數組中。 使塊對象可排序(我認為在Java中類似Comparable之類的東西)並對塊數組進行排序。 現在,將數組的每個條目寫入文件。 :)

您必須讀取文件並將每個元素存儲在數據結構中。

然后,您只需定義compare方法即可。

大致情況:

class ReadFile { 
   ...
   void read(){
      List<Product> list = ...
      while( readAllLines() ) {
        if( line.startWith("*")){ 
         list.add( new Product( line ));
        }
      }
      Collections.sort( list );
  }
  ...
}

然后在Product定義比較方法

class Product implements Comparable<Product> { 
  public Product( String fromLine ) { 
     // take values ... 
  }
  // attributes 
 ...
 // etc. 
 And then 
 public int compareTo( Product other ) { 
    return this.name.compareTo( other.name );
 }
}

您需要創建一個包含屬性的類:

  • 制造商
  • 類型
  • 顏色
  • 價錢

然后,您從文件中讀取數據並使用數據創建一個對象,然后將每個對象添加到ArrayList中,您可以在其中使用Collections.sort(...)方法。

然后,您的類可以實現Comparable接口,也可以使用BeanComparator Bean Comparator鏈接有一個簡單的示例,該示例實現Comparable,創建自定義Comparator或使用BeanComparator,因此您無需編寫任何自定義代碼。

我的建議是逐行讀取文件並創建“ Item”類型的普通POJO(其中Item只是您自己編寫的類,具有4個實例變量(所有Strings),即制造商,類型,顏色和價格)。

在閱讀文件時,您可以為文本文件中的每4行創建一個Item實例(即您的第一個Item的制造商=“ Violin”,類型=“ Electric”,顏色=“ Blue”,價格=“ $ 23”) )。

然后,您可以在創建它們時將它們放置在公共的ArrayList上,一旦完成讀取文件,就可以使用以下命令對其進行正確排序:

Collections.sort(itemList, new Comparator<Item>() {

   @Override
   public int compare(Item o1, Item o2) {
      return o1.getManufacturer().compareTo(o2);
   }
});

其中itemList是ArrayList<Item>

現在,您的列表將被排序,從而遍歷整個列表,只需將每個Item中的數據寫入到ouptut文件中,就這么簡單。

編輯根據要求,我將提供更多詳細信息,但是,盡管起初我說過我將按照您的要求使用手動排序,但我不再這樣做了。 相反,我將嘗試向您解釋Collections.sort方法,因為了解如何使用它非常重要。

因此,讓我們從Item類開始。 我只是將此類中的所有實例變量都公開,盡管您應該寧願使用常規的getter和setter方法將它們私有化(請注意,我也省略了package和import語句):

public class Item {
    public String manufacturer;        
    public String type;        
    public String colour;        
    public String price;

    public Item(String manufacturer, String type, String colour, String price) {
        this.manufacturer = manufacturer;
        this.type = type;
        this.colour = colour;
        this.price = price;
    }
}

該類將用於存儲我們希望排序的數據。 現在讓我們看看您的主要方法:

public static void main(String[] args) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader("inputFile.txt"));
        String nextLine = reader.readLine();
        List<Item> listOfItems = new ArrayList<Item>();

        while (nextLine != null) {
            if (!nextLine.equals("\n") && !nextLine.isEmpty()) {
                String manufacturer = nextLine;
                String type = reader.readLine();
                String colour = reader.readLine();
                String price = reader.readLine();

                Item newItem = new Item(manufacturer, type, colour, price);
                listOfItems.add(newItem);
            }
            nextLine = reader.readLine();
        }
        reader.close();
        Collections.sort(listOfItems, new Comparator<Item>() {

            @Override
            public int compare(Item o1, Item o2) {
                return o1.manufacturer.compareTo(o2.manufacturer);
            }
        });            
        PrintWriter writer = new PrintWriter("outputFile.txt");

        for (Item item : listOfItems) {
            writer.println(item.manufacturer);
            writer.println(item.type);
            writer.println(item.colour);
            writer.println(item.price);
            writer.println();
        }
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

好了,重要的是要注意Collections.sort的工作方式。 您向該方法傳遞一個集合(或更具體地說,在我們的示例中為List / ArrayList),它將為您排序該列表中的條目。 最大的問題是如何知道哪個Item對象應該排在第一,第二等等。由於我們要對制造商進行排序,因此需要告訴sort()使用其制造商實例變量來比較Item對象。

這是sort()的第二個參數定義的。 這個new Comparator<Item>部分告訴sort它將對Item對象進行排序。 sort()將使用我們定義的compare()方法進行排序。 它在排序過程中將項目相互比較,並且compare()方法告訴sort()只是將要分類的項目的制造商進行相互比較,並僅基於此進行排序。

如果您仍然不清楚,請特別向我詢問。 我認為,與向您展示如何編寫冒泡排序相比,了解此解決方案對您更有益。 如果您只想使用Google“ java氣泡排序”,則會彈出大量文章/帖子。

這一切都取決於您如何存儲數據。 如果僅使用原始文本文件,則必須編寫Java代碼來解釋數據,對其進行排序並吐出結果。 另外,您可以嘗試將數據加載到MySQL等數據庫中,然后通過Java與之交互。

假設您可以通過某種方式將數據加載到Java中,則可以執行以下操作:

public Instrument {
  public String manufacturer;
  public String type;
  public String color;
  public BigDecimal price;

  public Instrument(String manufacturer, String type, String color, BigDecimal price) {
    this.manufacturer = manufacturer;
    this.type = type;
    this.color = color;
    this.price = price;
  }

  public int compareTo(Object obj)
    Instrument temp = (Instrument)obj;

    return this.manufacturer.compareTo(temp.manufacturer);
  }
}

Instrument[] instruments = new Instrument[100]; // If you have 100 instruments in your file

instruments = LoadInstruments("INSRUMENTS.txt"); // Just an example of loading instruments

Arrays.sort(instruments);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM