I’ve created a basic class for you that will save the wins to a text file and retrieve them from a text file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WinsFileManager {
String path = System.getProperty("user.home").replace("\\", "\\\\") + "\\";
public int getWins(String fileName) {
String fullPath = path + fileName;
int wins = 0;
try {
wins = Integer.parseInt(new Scanner(new File(fullPath)).nextLine());
} catch (NumberFormatException e) {}
catch (FileNotFoundException e) {
wins = 0;
}
return wins;
}
public void saveWins(String fileName, int wins) {
PrintWriter out = null;
try {
out = new PrintWriter(path + fileName, "UTF-8");
out.println(wins);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here’s how you’d use an object of the above class from a different location.
public class test {
public static void main(String[] args) {
WinsFileManager manager = new WinsFileManager();
String fileName = "O Wins.txt";
manager.saveWins(fileName, 5);
System.out.println(manager.getWins(fileName));
}
}
The console output in the above example would be ‘5’.
I’ve done the hard part. Now it’s up to you to implement this into your program. To start off, whenever someone wins, I would retrieve the stored number of wins via the getWins
method, add one to that value, and then use the saveWins
method to store the incremented value. Keep in mind that even once you exit your program, the win values will be saved.
Note: There are much easier ways to do this if all you want to do is keep track of the wins within the lifespan of the program.
10
solved How to save results from the game to text file [closed]