I want to create a file in a directory in computer

2019-09-13 18:33发布

问题:

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?

回答1:

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
}


回答2:

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

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


回答3:

  • 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.