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