is there a way to add a specific directory to the Windows systemvariable %PATH%?
This doesn’t seem to work:
String[] cmd = { "cmd", "/c", "set", "PATH=\"%PATH%;c:\\test\"" };
Runtime.getRuntime().exec( cmd );
c:\test\ doesn’t appear in System.getenv(“PATH”); or in the output of
String[] cmd = { "cmd", "/c", "echo", "%PATH%" };
Runtime.getRuntime().exec( cmd );
What I need is to modify the %PATH%-variable for the current Java-Process under Windows. The reason is, that I need to load some native dll-files which cross-reference each other. So I’d like to add the application-path to the Windows environment.
The next thing I tried was a small JNI-Wrapper for the C-Function “putenv” which looks like this:
JNIEXPORT void JNICALL Java_com_splitscreen_AppletTest_PutEnv_putEnv
(JNIEnv *env, jobject jobj, jstring val) {
jboolean iscopy;
const char *mvalue = (*env)->GetStringUTFChars(
env, val, &iscopy);
putenv(mvalue);
}
This is how I call it:
final String curPath = System.getenv( "PATH" );
final PutEnv pe = new PutEnv();
pe.putEnv( "PATH=" + curPath + ";c:\test" );
final String newPath = System.getenv( "PATH" );
System.out.println( newPath );
But the pathes are equal. I’m not sure whether the Map of the Java-System-Environment isn’t updated or whether putenv didn’t work. Is there a way to check this?
The reason this doesn’t work is that the two
exec()invocations start two different shells; the one you set the path in isn’t the one you check it in.It’s difficult to change the permanent, systemwide path setting. But you can change the path for the duration of the invocation of one or more programs that you need it for.
Specifically, the thing to do is to write yourself a batch file (
.CMDor.BAT, as you please), set thePATHnear the beginning, follow that with whatever DOS/Windows commands you’d like executed with that path, and thenexec()that script file.Updating the PATH for the current Java process seems pretty pointless. Java, once running, doesn’t care about the path. Or are you running some library code that does?
If you are running DOS/Windows commands from Java using
exec(), the above trick will work.Update: OK, you have library code that for reasons of its own wants the PATH set just so, and you want to give it what it wants.
What I would consider here is to fire up a new JVM. You can use
exec(cmd, envp)to start up a new Java application (“yourself,” in a pinch) with a custom set of environment variables inenvp. Just copy the ones that are already there and manipulate the contents ofPATH, if any.The standard way to start up a new Java app is to create a new
ClassLoader, and there are various descriptions on how to accomplish that. But I’m not sure you can use that procedure to come up with a new environment – soexec-ing the JVM may not only be simpler, but possibly the only way.