Ina Ina - 4 months ago 19
Java Question

How to sort from text file and write into another text file Java

I have this textfile which I like to sort based on the number using Collection.sort().

This is my file to be sorted (avgGen.txt):

9.00,HC
27.00,P3
35.00,HC
91.00,P3
10.00,HC


Then my desired output into a new textfile (output.txt) is:

9.00,HC
10.00,HC
27.00,P3
35.00,HC
91.00,P3


But unfortunately the output that I got is:

9.00
10.00
27.00
35.00
91.00


where the string after is missing and i'm not sure how to fix it.

This is my code:

public class SortTest {
public static void main (String[] args) throws IOException{
ArrayList<Double> rows = new ArrayList<Double>();
ArrayList<String> convertString = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));

String s;
while((s = reader.readLine())!=null){
String[] data = s.split(",");
double avg = Double.parseDouble(data[0]);
rows.add(avg);
}

Collections.sort(rows);

for (Double toStr : rows){
convertString.add(String.valueOf(toStr));
}

FileWriter writer = new FileWriter("output.txt");
for(String cur: convertString)
writer.write(cur +"\n");

reader.close();
writer.close();

}
}


Please help.

Answer

When you read from the input file, you essentially discarded the string values. You need to retain those string values and associate them with their corresponding double values for your purpose.

You can

  1. wrap the double value and the string value into a class,
  2. create the list using that class instead of the double value alone
  3. Then sort the list based on the double value of the class using either a Comparator or make the class implement Comparable interface.
  4. Print out both the double value and its associated string value, which are encapsulated within a class

Below is an example:

static class Item {
    String str;
    Double value;

    public Item(String str, Double value) {
        this.str = str;
        this.value = value;
    }
}
public static void main (String[] args) throws IOException {
    ArrayList<Item> rows = new ArrayList<Item>();
    BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));

    String s;
    while((s = reader.readLine())!=null){
        String[] data = s.split(",");
        double avg = Double.parseDouble(data[0]);
        rows.add(new Item(data[1], avg));
    }

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

        public int compare(Item o1, Item o2) {
            if (o1.value < o2.value) {
                return -1;
            } else if (o1.value > o2.value) {
                return 1;
            }
            return 0;
        }
    });

    FileWriter writer = new FileWriter("output.txt");
    for(Item cur: rows)
        writer.write(cur.value + "," +  cur.str + "\n");

    reader.close();
    writer.close();
}
Comments