Last active
September 8, 2020 18:52
-
-
Save cwansart/10b7b1f9240396197e5df8b7dada4658 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package de.cwansart; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.OutputStream; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.Arrays; | |
import java.util.List; | |
public class Main { | |
private static final String HIGHSCORE_FILE = "highscore.class"; | |
private static List<Integer> highscore; | |
public static void main(String[] args) { | |
loadHighscore(); | |
printHighscore(); | |
// Überschreibe Highscore | |
highscore = Arrays.asList(55, 44, 33); | |
writeHighscore(); | |
printHighscore(); | |
} | |
private static void printHighscore() { | |
System.out.println("Hightscore"); | |
for (int i = 0; i < highscore.size(); i++) { | |
System.out.println("#" + (i+1) + ": " + highscore.get(i)); | |
} | |
} | |
private static void loadHighscore() { | |
// Prüfen ob die Highscore-Datei schon existiert. Wenn ja, dann laden, sonst mit einer leeren Liste anfangen. | |
if (Files.exists(Paths.get(HIGHSCORE_FILE))) { | |
try (InputStream inputStream = Files.newInputStream(Paths.get(HIGHSCORE_FILE)); | |
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) { | |
highscore = (List<Integer>) objectInputStream.readObject(); | |
} catch (IOException | ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} else { | |
// Highscore Liste mit 3x "0" erzeugen. | |
highscore = Arrays.asList(0, 0, 0); | |
} | |
} | |
private static void writeHighscore() { | |
try (OutputStream outputStream = Files.newOutputStream(Paths.get(HIGHSCORE_FILE)); | |
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) { | |
objectOutputStream.writeObject(highscore); | |
} catch (IOException exception) { | |
exception.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output should be something like this: