我想添加一种方法来存储游戏之间的积分(Java)

时间:2018-09-15 20:13:01

标签: java jpanel

我曾尝试过几种使用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) {     
    }
}

}
}

当游戏停止运行时,我接受了这个并命名。它似乎无能为力。

1 个答案:

答案 0 :(得分:1)

您实际上相距不远。 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);
}