0

I'm making a game, and that game requires a certain directory to be made in the AppData folder of the user's account. Now the problem is, I can't exactly know where to put it, as every user is different. This is on windows by the way. I want to know if I should write something special or...

File file = new File("C:\\Users\\%USER%\\AppData\\Roaming\\[gameName]");

Is there some special name that I have to give the "%USER%" (I just used that as an example), or is there something else I gotta do?

3 Answers 3

3

You can use the APPDATA environment variable which is usually "C:\Users\username\AppData\Roaming"

And you can get it using System.getenv() function :

String appData = System.getenv().get("APPDATA");

EDIT :

Look at this example (create a directory "myGame" and create a file "myGameFile" into this directory). The code is awful but it's just to give you an idea of how it works.

String gameFolderPath, gameFilePath;
gameFolderPath = System.getenv().get("APPDATA") + "\\myGame";
gameFilePath = gameFolderPath + "\\myGameFile";

File gameFolder = new File(gameFolderPath);
if (!gameFolder.exists()) {
    // Folder doesn't exist. Create it
    if (gameFolder.mkdir()) {
        // Folder created
        File gameFile = new File(gameFilePath);
        if (!gameFile.exists()) {
            // File doesn't exists, create it
            try {
                if (gameFile.createNewFile()) {
                    // mGameFile created in %APPDATA%\myGame !
                }
                else {
                    // Error
                }
            } catch (IOException ex) {
                // Handle exceptions here
            }
        }
        else {
            // File exists
        }
    }
    else {
        // Error
    }
}
else {
    // Folder exists
}
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean ? After that you can open your file (do not forget to check for errors and exceptions) and use it !
I added an example in my answer. I hope it's what you expected.
1

You can retrieve the current home user path using windows user.home property:

String homeFolder = System.getProperty("user.home")

1 Comment

Bonus: This is also platform independent by the way.
0
  • Firstly: You can not assume that C is the windows drive. The letter C for %HOMEDRIVE% is not mandatory.
  • Secondly: Neither can you assume that %USERHOME% is located on drive C:\ in folder Users.
  • Thirdly: If you use your construct and the first both points apply, your data wont be synched to the server based profile within a windows domain.

Use the windows environment variable %APPDATA%. It points to the path you want, but I am not certain that ALL windows versions have that variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.