Seeven
Seeven

Reputation: 1079

Create/write/read a text file external to the Jar archive

To save the state of a Java programmed video game in a text file (it is an exercise for a school project, I can't use serialization), I have to create a text file and write in it with PrintWriter, then read it with Scanner.

Until today I was creating the file in this directory :

PrintWriter vPW;
try {vPW = new PrintWriter("./saves/" + vFileName + ".txt");}
catch (final IOException pExp) {
        player.getGUI().println("Failed to create the file.");
        return;
}

Now that I had created a Jar archive of my project, I realize I can't create files in the archive while running the program.

I tried to create a file with these directories, but none of them worked :

vPW = new PrintWriter(System.getProperty("user.home") + "/gamesaves/" + vNomFichier + ".txt")

or

vPW = new PrintWriter("C:/saves/" + vFileName + ".txt")

How could I create, edit and read a text file somewhere on the system?

Upvotes: 0

Views: 2344

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61138

You probably need to create the folder first:

final File folder = new File(System.getProperty("user.home"), "gamesaves");
if(!folder.exists() && !folder.mkDirs()) {
   //failed to create the folder, probably exit
   throw new RuntimeException("Failed to create save directory.");
}
final File myFile = new File(folder, vNomFichier + ".txt");
final PrintWriter pw = new PrintWriter(myFile);

You can also check whether your application is allowed to write where you are asking it to with folder.canWrite(). If that returns false then the application does not have permission to write to that folder (or it does not exist).

Upvotes: 2

Related Questions