Changing AppData path (System Property)
I'm working on a launcher for the Minecraft game, what I would like to do is set the APPDATA (windows) location for the game. The value is not really changed, but it's modified for the program that executed the code. For example, it's very easy to achieve this on Mac OS X or Linux systems by changing the 'home' folders location using System.setProperty("user.home", dir); but how do you achieve this with the APPDATA folder on windows?
Modifying this location IS possible using Batch scripts like so; APPDATA=%CD%\minecraft.
The program/launcher is programmed using swing, and is not console based.
- APPDATA is a windows environment variable
Past answers from search: "java set environment variable":
How to add an environment variable in Java? ProcessBuilder environment variable in java How do I set environment variables from Java? Is it possible to set an environment variable at runtime from Java?
Trying to change the environment variables of the current process via brute-force native command execution, Runtime.getRuntime().exec("..."), will not work, because it executes the command in a separate process - environment changes will only apply within that process. Besides, System.getEnv() uses cached results, so the current java program most likely won't see the changes.
More specifically for you:
- Your launcher is a swing app
- Your game is a a swing app, with a frame to run the game in
I assume these are two separate apps and your launcher app starts a new process that runs game app.
If this is true:
Create a ProcessBuilder instance to launch the game process:
String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); ProcessBuilder builder = new ProcessBuilder( javaBin, "-cp", classpath, "com.example.MinecraftGame");
set environment variables for the game:
Map<String, String> env = pb.environment(); env.put("APPDATA", "%CD%\minecraft");
run the game:
Process process = builder.start(); process.waitFor(); return process.exitValue();
If this isn't the true:
- Maybe it should be, because java can control the environment variables for new processes that it spawns.
- If you must combine the two apps into one and run the game within the launcher app, then you need to set the environment for the launcher app before it's started. Use either the command line or a batch script that starts the launcher.
You can try this
Runtime.getRuntime().exec("cmd /c SET APPDATA=%CD%\minecraft");
You can change APPDATA for any child process you spawn. Use ProcessBuilder. It is possible, though difficult, to change it for the current process (use JNI). See this related question: Is it possible to set an environment variable at runtime from Java?