我曾多次尝试以多种方式使用java.io,但始终无法使其正常工作。我的想法是将获得的点数存储在一个名为save_data.txt的文件中,然后检索该列表中的3个最高整数,并将它们显示在排行榜上。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class TextFind {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
File file = new File("save_data.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(reader != null) {
reader.close();
}
}catch(IOException e) {
}
}
}
}
当游戏停止运行时,我调用了它。它似乎什么也做不了。
发布于 2018-09-16 05:35:22
实际上,你离得并不远。您的save_date.txt文件中是否有值?下面是一些使用Java 8的示例:
public static void main(String[] args) {
List<Integer> highScore = Arrays.asList(1, 2); // Dummy values
Path filePath = Paths.get("save_data.txt"); // Your saved data
// Transform available high scores to a single String using the System line separator to separated the values and afterwards transform the String to bytes ...
byte[] bytes = highScore.stream().map(Object::toString).collect(Collectors.joining(System.lineSeparator())).getBytes();
try {
// Write those high score bytes to a file ...
Files.write(filePath, bytes, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
List<String> lines = Collections.emptyList();
try {
// Read all available high scores lines from the file ...
lines = Files.readAllLines(filePath);
} catch (IOException e) {
e.printStackTrace();
}
int skipLines = Math.max(lines.size() - 3, 0); // You only want the three highest values so we use the line count to determine the amount of values that may be skipped and we make sure that the value may not be negative...
// Stream through all available lines stored in the file, transform the String objects to Integer objects, sort them, skip all values except the last three and sort their order descending
highScore = lines.stream().map(Integer::valueOf).sorted().skip(skipLines).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
// Print the result
highScore.forEach(System.out::println);
}
https://stackoverflow.com/questions/52348474
复制相似问题