简体   繁体   中英

How do I sort a text file alphabetically?

For example, I want this data:

     Manufacturer : - Violin

     Type : - Electric

     Colour: - Blue

     Price : $23



     Manufacturer : - Guitar

     Type : - Electric

     Colour: - Red

     Price : $54

To look like:

     Manufacturer : - Guitar

     Type : - Electric

     Colour: - Red

     Price : $54



     Manufacturer : - Violin

     Type : - Electric

     Colour: - Blue

     Price : $23

(Note how the violin information comes below the guitar since alphabetically it comes after "G"uitar.)

The complete code to solve this problem is going to be relatively long for a response here, but I can give you some directions:

First create a class that holds information about each of your objects "Violin", "Guitar", etc. Basically, that class could look like this:

public class BlockOfText
{
   public String name;

   public String block;
}

, where the "name" is "Guitar" and "Violin" and the "block" is the entire block. Now read each block from the input file and keep them in an array. Make the block object sortable (I think in java there is something like Comparable or so) and sort that array of blocks. Now write each entry of the array into a file. :)

You have to read the file and store each element in a data structure.

Then you just define the compare method and that's it.

Something along the lines:

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

And then define the compare method in 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 );
 }
}

You need to create a class that contains the properties:

  • Manufacturer
  • Type
  • Color
  • Price

Then you read the data from the file and create an Object with the data, then add each object to an ArrayList where you can use the Collections.sort(...) method.

Your class can then implement the Comparable interface or you can use the BeanComparator . The Bean Comparator link has a simple example of implementing Comparable, creating a custom Comparator or using the BeanComparator so you don't need to write any custom code.

My suggestion would be to read the file in line by line and create normal POJOs of type "Item" (where Item is just a class you have written yourself that has 4 instance variables (all Strings), ie manufacturer, type, colour and price).

As you read in the file you can create an Item instance for every 4 lines in your text file (ie your first Item would have manufacturer = "Violin", type = "Electric", colour = "Blue" and price = "$23").

You could then just put each item onto a common ArrayList as you create them and once you have finished reading the file you could use the following to sort it correctly:

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

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

where itemList is an ArrayList<Item> .

Your list will now be sorted so loop through it and just write the data in each Item to your ouptut file, easy as that.

EDIT As requested, I will provide more detail, however, although originally I said that I would use manual sorting as you requested, I'm not going to do that anymore. Instead I will try explain the Collections.sort method to you since it is really important that you know how to use this.

So let's start of with the Item class. I will just make all the instance variables in this class public although you should probably rather have them private with the usual getter and setter methods (note that I am also omitting package and import statements):

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;
    }
}

This class will be used to store the data that we wish to sort. Now let us have a look at your main method:

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();
    }
}

Ok so the important part is to note how Collections.sort works. You pass this method a collection (or more specifically in our case a List / ArrayList) and it will sort the entries in that list for you. The big question is how does it know which Item object should come first, second, etc. Since we want to sort on the manufacturer, we need to tell sort() to compare Item objects using their manufacturer instance variables.

This is what the second argument to sort() defines. This new Comparator<Item> part tells sort that it will be sorting Item objects. sort() will use the compare() method we defined to do this sorting. It compares the items to one another during its sorting process and the compare() method is telling sort() to just compare the manufacturers of the Items being sorted to one another and sort based only on that.

If something is still not clear to you please ask me about that specifically. I think understanding this solution will be more beneficial to you than showing you how to write a bubble sort. If you want that just google "java bubble sort" and tons of articles / posts will pop up.

That all depends on how you have the data stored. If you are simply working with a raw text file, you would have to write Java code to interpret your data, sort it, and spit out the results. Alternatively, you could attempt to load your data into a database such as MySQL, then interact with it via Java.

Assuming you can load the data into Java somehow, you could do something like:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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