I don't know is there any way in java to save & load the whole game/app using only one script(java file,class...)?
For example if I create many int's and string's in lots of java files, Is there any way to save them all using only one script. And when I turn off the game/app (System.exit(1);
) and when I go back to game it will load by itself (I won't lose my stats.).
Is there any way to do that?
You should not save your game data to a Java file. It makes no sense. Java files are meant to store Java source code, not your game data.
You should write your game data to some other files and read it when the program starts.
You basically use ObjectOutputStream
and ObjectInputStream
to do this.
Just before the user closes the program, you create a new ObjectOutputStream
:
FileOutputStream fos = new FileOutputStream("The/Path/That/You/Want/The/Data/File/To/be");
ObjectOutputStream stream = new ObjectOutputStream(fos);
Then you put all your game data (your ints and strings) into one single POJO that implements Serializable
. After that, write this POJO to that file.
This is the POJO class:
public class GameData implements Serializable {
private int int1, int2, int3;
private String s1, s2, s3;
// getters for the fields
public GameData(int int1, int int2, int int3, String s1, String s2, String s3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.s1 = s1;
this.s2 = s2;
this.s2 = s3;
}
}
And you save the data like this:
GameData data = new GameData(someInt1, someInt2, someInt3, someStr1, someStr2, someStr3);
stream.writeObject(data);
When you want to read the data back, just create a FileInputStream
and an ObjectInputStream
and cast the read object to GameData
and you can get all your ints and strings back!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments