0

I need to permanently modify the system's PATH environment variable. For this I'm planning to check if the folder I'm about to add already exists and only if it doesn't, it gets added.

String pathToAdd = "C:\\Example\\bin";
String pathContents = getPathSystemEnvironmentValue();
if(!pathContents.contains(pathToAdd))
{
    pathContents += ";" + pathToAdd;
}

setPathSystemEnvironmentValue(pathContents);

Unfortunately, I don't know how to retrieve and set the PATH environment variable conveniently. I've seen that it can be done by using the setx command but it would not use any Java code and it's obviously not platform-independent. I also want to avoid calling external batch files. I know that Java wasn't meant to do native tasks like this but is there a decent solution though? Possibly compatible with Linux as well.

Community
  • 1
  • 1
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
  • Why would you want to do this (especially permanently)? – tjalling Aug 25 '15 at 13:44
  • @tjalling I'm making a software utility that helps installing other software on the system which needs environment variables to be set – BullyWiiPlaza Aug 25 '15 at 13:45
  • I was way too hasty casting my duplicate flag. Please decline the flag! – Rainbolt Aug 25 '15 at 13:47
  • Permanently changing environment variables is not possible in a platform independent way. Windows stores those in the registry, Linux usually uses `/etc/profile` or similar. *BSDs have `login.conf`. And of course there's systemd ... – dhke Aug 25 '15 at 13:50
  • @BullyWiiPlaza Why not install that software using the target OS' normal installation locations? (purely in response to PATH, not talking about custom environment variables) – tjalling Aug 25 '15 at 13:51
  • @Rainbolt The answers there change the environment for the current process (and children, [Java version](https://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java)). The tricky bit is the *permanent*. – dhke Aug 25 '15 at 13:54

0 Answers0