setting user environment variable on windows/linux system by java programming

HI,
How could I set/change windows/linux system user environment variable  by java programming?
LVL 15
fsze88Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mick BarryJava DeveloperCommented:
As I said in the previous question you can't as you cannot access the users shell that started your application

0
Mick BarryJava DeveloperCommented:
you might be able to do it with jni, never tried

some good info here

http://mindprod.com/jgloss/environment.html

0
see4me2002Commented:
A possible way to ease the burden would be to factor out a method

void setUpEnvironment(ProcessBuilder builder) {
    Map<String, String> env = builder.environment();
    // blah blah
}

and pass any ProcessBuilders through it before starting them.

Also, you probably already know this, but you can start more than one process with the same ProcessBuilder. So if your subprocesses are the same, you don't need to do this setup over and over
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

CEHJCommented:
In Windows with the command line programme reg.exe. In Linux you'd have to set future env vars for all shell instances by writing to one of the shell initialization files such as ~/.bashrc
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
fsze88Author Commented:
three questions
1) I needs set System.getProperty("user.home"); before launch ProcessBuilder and ProcessBuilder.start();
2)
it works on new ProcessBuilder("notepad");        
but not new ProcessBuilder("cmd /C REG ADD HKEY_CURRENT_USER\\Environment /v hello /t reg_sz /d \"I love you\" /f");  
3) at statement System.out.println(environment.toString());   // it show up all of system & user environment variables

Thank you
import java.io.*;
import java.util.*;
 
public class ProcessBuilderTest {
 
    public static void main(String[] args) throws Exception {
        System.getProperty("user.home");
//        ProcessBuilder builder = new ProcessBuilder("cmd /C REG ADD HKEY_CURRENT_USER\\Environment /v hello /t reg_sz /d \"I love you\" /f");  // it doesn't works
        ProcessBuilder builder = new ProcessBuilder("notepad");        // It works
        Map<String, String> environment = builder.environment();
 
//        environment.put("path", ";"); // Clearing the path variable;
//        environment.put("path", "D:\\Java\\Java6.0\\bin;");
 
        builder.directory(new File("c:\\"));
//            System.out.println(environment.toString());   // it can show system & user environment variables 
        Process p = builder.start();
        writeProcessOutput(p);
    }
 
    static void writeProcessOutput(Process process) throws Exception{
        InputStreamReader tempReader = new InputStreamReader(
            new BufferedInputStream(process.getInputStream()));
        BufferedReader reader = new BufferedReader(tempReader);
        while (true){
            String line = reader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }		
    }
 
}

Open in new window

0
Mick BarryJava DeveloperCommented:
as I told you already that won't work, you can't change environment values
0
fsze88Author Commented:
objects, following is works on windows xp sp3
        try {
            System.getProperty("user.home");
            System.out.println("user environment variable : " +  System.getenv("prefix"));
            Runtime.getRuntime().exec("cmd /C REG ADD HKEY_CURRENT_USER\\Environment /v hello /t reg_sz /d \"I love you\" /f");
        } catch (IOException e) {
        }
0
Mick BarryJava DeveloperCommented:
if you want to set the property just for the process you are creating then you can set it in the environment but thats about all you can do.

What exactly are your requirements

0
Mick BarryJava DeveloperCommented:
it changes the registry, it doesn't change the environment of the current shell.
0
fsze88Author Commented:
objects, writing user environment variable is indeed. I don't mind to write it by register.
About current shell, I have a problem if I writing user environment variable (uev) by
            Runtime rt = Runtime.getRuntime();
            Process p = rt.exec("cmd /C set abc=def");

I am not able to read it back by
            Process p2 = rt.exec("cmd /C echo %abc%");
            System.out.println("user environment variable abc : " +  writeProcessOutput2(p2) );
            System.out.println("user environment variable abc : " +  System.getenv("abc") );

How to read it back, thank you

    static String writeProcessOutput2(Process process) throws Exception{
        String returnValue = "";
        InputStreamReader tempReader = new InputStreamReader(
            new BufferedInputStream(process.getInputStream()));
        BufferedReader reader = new BufferedReader(tempReader);
        while (true){
            String line = reader.readLine();
            returnValue += line;
            if (line == null)
                break;
//            System.out.println(line);
        }
        return returnValue;
    }

Open in new window

0
Mick BarryJava DeveloperCommented:
> objects, writing user environment variable is indeed. I don't mind to write it by register.

be aware its changing for *all* newly created shells

If you want to change users environment then java is not the tool for the job

> I am not able to read it back by

Thats because it is only changing the environment for that shell (the one you run the set command in)


What is it you are trying to do exactly.

0
fsze88Author Commented:
be aware its changing for *all* newly created shells
> Yes, that is what I want. Save it by one of user, all of others are able to read it on that computer and needed to be used in the future
Thats because it is only changing the environment for that shell (the one you run the set command in)
> Yes, it is running in same Runtime,  Runtime rt = Runtime.getRuntime();
0
Mick BarryJava DeveloperCommented:
No, each process starts a new shell. There is no shared shell for a runtime instance

0
CEHJCommented:
As i mentioned in this and your last question (where you seemed to accept answers to a different problem) on the subject, the only way you can do this in Windows is to use the registry, even if you only want to set a temporary variable.

If you told me more about what you're trying to do, it might help.

http://catb.org/esr/faqs/smart-questions.html

(Particularly the para beginning 'Describe the goal...' )
0
fsze88Author Commented:
CEHJ,
relax. yes, you solved my question already (windows xp pro sp3).
But, I still looking for setting user environment variable in linux system.
Even, if possible is there some way in java programming like System.getenv(....) is the best.

after all, no shell command in linux instead of editing ~/.bashrc? I think it have.
0
CEHJCommented:
>>But, I still looking for setting user environment variable in linux system.

It's really the same situation there, except the 'global' solution is, yes, as you say, to edit shell config files. You can't set the current shell
0
Mick BarryJava DeveloperCommented:
> Even, if possible is there some way in java programming like System.getenv(....) is the best.

no

> after all, no shell command in linux instead of editing ~/.bashrc? I think it have.

there isn't and there are many different shells. you're approach appears flawed, you may be better up setting up the environment using your own mechanism and then have the shell that needs the vars to load themfrom there.
Java just isn't the tool for changing the environment setting, so many easier ways to do that (eg. just use a script)

0
fsze88Author Commented:
0
Mick BarryJava DeveloperCommented:
which is what I suggested above, ie. you need to manage the environment yourself
0
fsze88Author Commented:
STILL NOT SOLVE ABOUT SETTING USER ENVIRONMENT VARIABLE ON WINDOWS XP
I just discovered type in REG ADD HKEY_CURRENT_USER\Environment /v testing /t reg_expand_sz /d 123 /f in dos command or
by java Runtime.getRuntime().exec("cmd /C REG ADD HKEY_CURRENT_USER\\Environment /v testing /t reg_expand_sz /d 123 /f");
It just added key/value into register and show up in system/advanced/env var panel, but environment variable is still not effective!

Anyone can help!?
0
CEHJCommented:
You'd only be able, via the registry, to set environment variables for all *subsequent* shells - not the one you're in
0
Mick BarryJava DeveloperCommented:
> It just added key/value into register and show up in system/advanced/env var panel, but environment variable is still not effective!

thats what I have been telling you :) You cannot change the environment
0
fsze88Author Commented:
I searching on internet.
I downloaded a file setenv.exe , place it in path and run setenv /u test 123. That's fine for setting user environment variable from command prompt and java desktop programming.
also, we can try to run from powershell or TCC LE instead of cmd.exe. It also works!
http://www.microsoft.com/downloads/details.aspx?FamilyID=c913aeab-d7b4-4bb1-a958-ee6d7fe307bc&displaylang=en#filelist
http://www.jpsoft.com/download.htm

up to now, I found three ways to solve it out
0
Mick BarryJava DeveloperCommented:
depends on *which* shell it is you want to change the environement :)
When we have need to control the user environment from Java we found the simplest was to manage the environment using the Preferences api and passing that environment to any process that needed it. That works for us on all platforms regardless of the shell we are using.


0
fsze88Author Commented:
we found the simplest was to manage the environment using the Preferences api
YES, that's the best way to do it. But I tried

            System.getProperty("user.home");
//            Properties props=new Properties(System.getProperties());
//            props.put("test", "test");
//            props.setProperty("test", "test");
doesn't works. But also, I don't like to use jni

.......
0
CEHJCommented:
>>I downloaded a file setenv.exe

That's good. Will it set the var for the current shell too? So that getenv works after previously returning null?
0
fsze88Author Commented:
That's good. Will it set the var for the current shell too? Sorry, no. It works on second command prompt after run setenv /u test 123
So that getenv works after previously returning null? at second command prompt run echo %test% , it return 123
0
CEHJCommented:
>>Sorry, no. It works on second command prompt after run setenv /u test 123

Well of course you don't need a special program to do that - just use reg as i mentioned
0
fsze88Author Commented:
no, I run REG ADD HKEY_CURRENT_USER\\Environment /v hello /t reg_sz /d \"I love you\" /f
is not works at second command prompt as stated at #24459229 ....
0
CEHJCommented:
:-)

>>is not works at second command prompt as stated at #24459229 ....

Does it actually get written to the registry at all? That could be a privileged operation
0
fsze88Author Commented:
it written to registry, but can't get it back by echo %test% on second command prompt
0
fsze88Author Commented:
so I using setenv.exe is the most easiest way, I think
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.