按照数字从高到低的顺序排列文件,保留其他信息。

huangapple go评论91阅读模式
英文:

Ordering a File from highest number to lowest, retaining the other information

问题

我正在寻找一种方法,能够读取文件并重新写入同一个文件,但要考虑文件内的所有信息,以便将其按从高到低的顺序进行排序。

以下是你的代码,无需翻译:

/*Scores*/
    Mathew: 540
    Stacy: 070
    Andre: 761
    Alfred: 340

我想将其变为:

/*Scores*/
Andre: 761
Mathew: 540
Alfred: 340
Stacy: 070

对于每个级别,我以以下方式编写文件:

public void scoreWrite(int levelID) throws IOException {
    File Highscores = new File("Scoreboard/Level_" + levelID + "_Highscore.txt");

    if(Highscores.createNewFile()) {
        FileWriter highscoreWriter = new FileWriter(Highscores, false);
        highscoreWriter.write("/*---Highscores---*/ \n \n");
        highscoreWriter.write(SokobanGame.getInstance().getPlayerName()+ "'s " + "score: " + getScore() + " points;\n");
        highscoreWriter.close();
    } else {
        Highscores = new File("Scoreboard/Level_" + levelID + "_Highscore.txt");
        FileWriter highscoreWriter = new FileWriter(Highscores, true);
        highscoreWriter.write(SokobanGame.getInstance().getPlayerName()+ "'s " + "score: " + getScore() + " points;\n");
        highscoreWriter.close();
    }
}

但是现在我对如何进行排序感到完全茫然... 任何帮助将不胜感激!

英文:

I'm looking for a way to be able to read a file and rewrite the same file but taking into account all the information inside it to order it from highest to lowest

/*Scores*/
    Mathew: 540
    Stacy: 070
    Andre: 761
    Alfred: 340

So that would be how it's written in my .txt file and I want it to be:

/*Scores*/
Andre: 761
Mathew: 540
Alfred: 340
Stacy: 070

I'm writing the file for each level, the following way:

public void scoreWrite(int levelID) throws IOException {
	File Highscores = new File("Scoreboard/Level_" + levelID + "_Highscore.txt");
	//		Level_0_Highscore.txt

	if(Highscores.createNewFile()) {
		FileWriter highscoreWriter = new FileWriter(Highscores, false);
		highscoreWriter.write("/*---Highscores---*/ \n \n");
		highscoreWriter.write(SokobanGame.getInstance().getPlayerName()+ "'s " + "score: " + getScore() + " points;\n");
		highscoreWriter.close();
	}else {
		Highscores = new File("Scoreboard/Level_" + levelID + "_Highscore.txt");
		FileWriter highscoreWriter = new FileWriter(Highscores, true);
		highscoreWriter.write(SokobanGame.getInstance().getPlayerName()+ "'s " + "score: " + getScore() + " points;\n");
		highscoreWriter.close();
	}
}

But now for the way to order, I'm at a complete loss... Any help would be appreciated!

答案1

得分: 3

你可以使用 SortedMap 来简化代码。首先创建一个 SortedMap

SortedMap<Integer, String> map = new TreeMap<>();
map.put(540, "Mathew");
map.put(070, "Stacy");

现在在方法中:

File Highscores = new File("Scoreboard/Level_" + levelID + "_Highscore.txt");

String save = map.entrySet().stream() // 遍历 map
        .map(s -> s.getValue() + ": " + s.getKey()) // 映射为所需格式
        .collect(Collectors.joining("\n")); // 连接元素

Files.writeString(Highscores.toPath(), save);

以下是从一个文件读取内容并写入另一个文件的方法:

Path path = Paths.get("Scoreboard/Level_" + levelID + "_Highscore.txt");

String save = Files.readAllLines(path).stream() // 从输入文件流式处理所有行
        .map(s -> Map.entry(Integer.parseInt(s.split(": ")[1]), s.split(": ")[0].strip())) // 分割并映射为 Map.Entry
        .sorted(Map.Entry.<Integer, String>comparingByKey()) // 排序
        .map(entry -> entry.getValue() + ": " + entry.getKey()) // 映射为所需格式
        .collect(Collectors.joining("\n")); // 连接为字符串

Files.writeString(Highscores.toPath(), save);
英文:

You can simplify it using a SortedMap. First create a SortedMap:

SortedMap&lt;Integer, String&gt; map = new TreeMap&lt;&gt;();
map.put(540, &quot;Mathew&quot;);
map.put(070, &quot;Stacy&quot;);

Now in the method:

File Highscores = new File(&quot;Scoreboard/Level_&quot; + levelID + &quot;_Highscore.txt&quot;);

String save = map.entrySet().stream() // stream over map
		.map(s -&gt; s.getValue() + &quot;: &quot; + s.getKey()) // map to required format
		.collect(Collectors.joining(&quot;\n&quot;)); // join the elements

Files.writeString(Highscores.toPath(), save);

Here is how you can do it by reading from one file and writing to another:

Path path = Paths.get(&quot;Scoreboard/Level_&quot; + levelID + &quot;_Highscore.txt&quot;);

String save = Files.readAllLines(path).stream() // stream all lines from input file
		.map(s -&gt; Map.entry(Integer.parseInt(s.split(&quot;: &quot;)[1]), s.split(&quot;: &quot;)[0].strip())) // split and map to Map.Entry
		.sorted(Map.Entry.&lt;Integer, String&gt;comparingByKey()) // sort
		.map(entry -&gt; entry.getValue() + &quot;: &quot; + entry.getKey()) // map to required format
		.collect(Collectors.joining(&quot;\n&quot;)); // collect back to string

Files.writeString(Highscores.toPath(), save);

答案2

得分: 2

太好的问题,这可以很容易地解决。只需将文件读取为表示每行的字符串对象集合。然后按 :空格 字符拆分行,获取分数值并进行比较。然后可以通过连接这些值将其简单地映射回字符串列表。最后,您可以使用 Files.write 进行写入!

Path path = Paths.get("Scoreboard/Level_" + levelID + "_Highscore.txt");

List<String> lines = Files.readAllLines(path);

List<String> linesOrdered = lines.stream()
        .map(line -> line.replaceAll(" ", "").split(":"))
        .sorted(Comparator.comparingInt(strings -> Integer.parseInt(strings[1])))
        .map(values -> String.join(" ", values))
        .collect(Collectors.toList());

Files.write(path, linesOrdered);
英文:

great question, and this can be easily solved. Simply read the File as a Collection of String objects that represent each line. Then split the line by the : or whitespace character and get the score value and compare based off of that. Then you can simply map back to a List of String by joining the values. You can then write using Files.write!

Path path = Paths.get(&quot;Scoreboard/Level_&quot; + levelID + &quot;_Highscore.txt&quot;);

List&lt;String&gt; lines = Files.readAllLines(path);

        List&lt;String&gt; linesOrdered = lines.stream()
                .map(line -&gt; line.replaceAll(&quot; &quot;, &quot;&quot;).split(&quot;:&quot;))
                .sorted(Comparator.comparingInt(strings -&gt; Integer.parseInt(strings[1])))
                .map(values -&gt; String.join(&quot; &quot;, values))
                .collect(Collectors.toList());

Files.write(path, linesOrdered);

huangapple
  • 本文由 发表于 2020年5月19日 20:42:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61891312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定