Set Windows PATH environment variable at runtime in Java

I have a java program that runs an executable using the Runtime.exec () method. I am using an option that takes a set of command line options as one argument, and some environment variables as another argument.

The environment variable I'm trying to set is the path, so I pass "PATH = C: \ some \ path". This does not work. Is there any trick to this or to any alternatives. Unfortunately, I stick with Java 1.4.

+4
source share
4 answers

use http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#getenv%28java.lang.String%29 to get the environment and fix it, then use the fragrance [ http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec%28java.lang.String,%20java.lang.String[†,%20java.io. File% 29] [1] to execute exec.

this works with a batch file that has a path in it.

package p; import java.util.*; public class Run { static String[] mapToStringArray(Map<String, String> map) { final String[] strings = new String[map.size()]; int i = 0; for (Map.Entry<String, String> e : map.entrySet()) { strings[i] = e.getKey() + '=' + e.getValue(); i++; } return strings; } public static void main(String[] arguments) throws Exception { final Map<String, String> env = new HashMap<String, String>(System.getenv()); env.put("Path", env.get("Path") + ";foo"); final String[] strings=mapToStringArray(env); Runtime.getRuntime().exec("cmd /C start foo.bat",strings); } } 
+7
source

If "PATH = C: \ some \ path" appears in your source code, this would not be true, since it tried to avoid the "s" and "p" in this line, you should use "PATH = C: \\ some \\ path "instead (discarding slashes). In addition, you do not want to pass it as a string directly, but as an array of strings (most likely, this is the only string in it).

+2
source

If you want to change the Path variable in windows, you should take a look at JNI_Registry: http://www.trustice.com/java/jnireg/

This is a Java binding to the Windows registry API and has a very small footprint. I used it for my current project and it works great.

+2
source

One solution might be to add an extra command to "exec" where you set the path ... as in the example found here: http://www.neowin.net/forum/topic/620450-java-runtimegetruntimeexec-help/

excerpt:

  cmd = new String[7]; cmd[0] = "cmd"; cmd[1] = "/C"; cmd[2] = "set PATH=C:\\Program Files\\Java\\jdk1.6.0_04\bin"; cmd[3] = "copy " + "\"" +path + "\\" +name+ "\"" + " C:\\java"; cmd[4] = "chdir C:\\java"; cmd[5] = "javac *.java"; cmd[6] = "jar cmf mainClass.txt"+" name"+".jar *.class"; try{ Runtime.getRuntime().exec(cmd); 
+1
source

Source: https://habr.com/ru/post/1308411/


All Articles