简体   繁体   中英

Java: How to sort the txt file?

I need your help again. how do I sort the records in the txt file in Java?

Here's the code how i save the scores

try {
    File highscore = new File("highscore.txt");
    PrintWriter output = new PrintWriter(new FileWriter(highscore, true));

    if (highscore.exists()) {
        System.out.println();
        System.out.println("High Score:");
    }

    output.println(name + " - " + totalScore);
    output.close();
} catch (IOException e) {
    System.out.println(e);
}

and here's the code how I display the scores

try {
    FileReader fr = new FileReader("highscore.txt");
    BufferedReader br = new BufferedReader(fr);
    String s;

    while ((s = br.readLine()) != null) {
        System.out.println(s);
    }

    br.close();
} catch (IOException e) {
    System.out.println(e);
}

My current output is:

Player1 100
Player2 200
Player3 50

And i want to sort the score from highest to lowest, how do I go about that? thank you in advance!

the output that I want to get is:

Player2 200
Player1 100
Player3 50

As per @luk2302 and @yshavit, you'll need to change the reading loop into something else:

while ((s = br.readLine()) != null) {
    // 1. Create a custom object from found lines and push them into a list
}
// 2. Sort the list
// 3. Print the list

You might want to change the saving routine too but that wasn't asked so I'm skipping it.

i would recommend to use the java sorting function, in this case I would create an object Highscore.class which contains name and score.

public class Highscore {
    private String name;
    private Integer score;

    public Highscore(String name, Integer score) {
        this.name = name;
        this.score = score;
    }

    // getters...
 }

Having that object, you have to create List<Highscore> and sort over that one...

List<Highscore> highscores = new ArrayList();
//add all highscores e.g. highscores.add(new Highscore(name, totalScore));

highscores.sort(Comparator.comparing(Highscore::getScore));

After sorting you can put the highscores into a file.

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