英文:
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<Integer, String> map = new TreeMap<>();
map.put(540, "Mathew");
map.put(070, "Stacy");
Now in the method:
File Highscores = new File("Scoreboard/Level_" + levelID + "_Highscore.txt");
String save = map.entrySet().stream() // stream over map
.map(s -> s.getValue() + ": " + s.getKey()) // map to required format
.collect(Collectors.joining("\n")); // 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("Scoreboard/Level_" + levelID + "_Highscore.txt");
String save = Files.readAllLines(path).stream() // stream all lines from input file
.map(s -> Map.entry(Integer.parseInt(s.split(": ")[1]), s.split(": ")[0].strip())) // split and map to Map.Entry
.sorted(Map.Entry.<Integer, String>comparingByKey()) // sort
.map(entry -> entry.getValue() + ": " + entry.getKey()) // map to required format
.collect(Collectors.joining("\n")); // 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("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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论