How to set environment variables using java program

Hi all
I want to set environment variables on windows 98/200/xp system, such as path and classpath using a java program.
How to do this using a java program.
Any body plz helppppppppp.

#1 05-02-2003, 07:38 AM
Goodz13 Join Date: Jan 2002, Posts: 985
Location: Halifax, NS, Canada
Reputation:
Java FAQ's and tutorials
Java FAQ's
Path and ClassPath:
PATH
In Windows 9x you would set it up in the autoexec.bat file
ie.
SET PATH=%PATH%;c:\jdk1.4.2\bin\;
where c:\jdk1.4.2\ is the path where you installed Java.
In Windows 2000 and XP
Right click on My Computer->Properties->Advanced Tab->Environment Variables... Button.
If you see a PATH in System Variables, click that and edit it. If you don't, you will need to create a new System variable.
It should look something like this:
%SystemRoot%\system32;%SystemRoot%;c:\jdk1.4.2\bin\;
Any querry email me to [email protected]
Answer by
Rajasekhar Goli
DS UNICS Infotech

Similar Messages

  • Setting persitent system environment variables using java program

    hai,
    Iam tryng to write installation for an application,which require to set some persistent system environment variables using java program. I have tried using set command Runtime.getRuntime().exec("cmd /c set blah blah "),but this applies only to that particular DOS promt only,i presume.And this is not perisistent.please do help.
    Biju

    The solution I proposed worked only on Windows XP/2003.
    The following solution will work on Windows NT/2000/XP/2003 with JDK 1.2+.
    1- Download the [url http://www.gjt.org/download/time/java/jnireg/registry-3.1.3.zip]JNIRegistry zipped archive.
    2- Open the registry-3.1.3.zip file and extract in the folder of your choice ( Eg. c:\setenv ) only the 2 first files (when sorted by path): ICE_JNIRegistry.dll and registry.jar.
    You don't need to keep the folder tree in the extraction.
    3- Create the following SetEnv.java file in the same folder ( Eg. c:\setenv ).
    import com.ice.jni.registry.Registry;
    import com.ice.jni.registry.RegistryKey;
    import com.ice.jni.registry.RegStringValue;
    import com.ice.jni.registry.RegistryValue;
    public class SetEnv
        static final String REG_HKLM_SUBKEY_NAME = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
        public static void main(String[] args)
        throws Exception
            new SetEnv().exec(args);
        void exec(String[] args)
        throws Exception
            if (args.length != 2)
                throw new IllegalArgumentException("\n\nUsage: java SetEnv {varName} {varValue}\n\n");
            String varName = args[0];
            String varValue = args[1];
            RegistryKey key = null;
            RegStringValue value;
            try
                key = Registry.HKEY_LOCAL_MACHINE.openSubKey(REG_HKLM_SUBKEY_NAME, RegistryKey.ACCESS_ALL);
                value = new RegStringValue(key, varName, RegistryValue.REG_EXPAND_SZ);           
                value.setData(varValue);
                key.setValue(value);
                key.flushKey();
            finally
                try { key.closeKey(); }
                catch (Exception e) {}
    }4- Compile it.
    javac -classpath .;registry.jar SetEnv.java
    5- Run it. varName and varValue are strings of your choice.
    java -classpath .;registry.jar -Djava.library.path=. SetEnv varName varValue

  • Setting windows environment variables from Java program

    Is there any way to set environment variables from Java program in Windows? Any help is appreciated.
    Here is my situation:
    I need to decrypt an encrypted Oracle user password in a batch file which will be used while running a sql script with sqlplus. I was planning to have bat file which will call a Java program decrypt the password and set it as an env variable in windows which will be available while calling sqlplus.
    thanks

    Runtime.exec has a lot of overloadings. Two of them
    allows you to specify the environment variables.
    exec
    public Process exec(String[] cmdarray,
    String[] envp,
    File dir)
    throws IOExceptionExecutes the specified command and
    arguments in a separate process with the specified
    environment and working directory.
    cmdarray - array containing the command to call and
    its arguments.
    envp - array of strings, each element of which has
    environment variable settings in format name=value.
    dir - the working directory of the subprocess, or null
    if the subprocess should inherit the working directory
    of the current process.
    I had this sample program:
    public class SetVarExample {
    public static void main (String[] args) throws Exception {
         String[] cmd_env= new String[] {"password="+"ABCD","Path=C:\\Sun\\AppServer\\jdk\\bin"};
         String cmd = "cmd /c SET ";
         Runtime.getRuntime().exec(cmd,cmd_env);
    System.out.println( "Finish ...." );
    I tried it in a command prompt. But looks like when the program exits, it's a whole new process and so it does not retain the env variables set in the java program.
    Any suggestions? Am I doing it worng?
    thanks

  • How to set proxy authentication using java properties at run time

    Hi All,
    How to set proxy authentication using java properties on the command line, or in Netbeans (Project => Properties
    => Run => Arguments). Below is a simple URL data extract program which works in absence of firewall:
    import java.io.*;
    import java.net.*;
    public class DnldURLWithoutUsingProxy {
       public static void main (String[] args) {
          URL u;
          InputStream is = null;
          DataInputStream dis;
          String s;
          try {
              u = new URL("http://www.yahoo.com.au/index.html");
             is = u.openStream();         // throws an IOException
             dis = new DataInputStream(new BufferedInputStream(is));
             BufferedReader br = new BufferedReader(new InputStreamReader(dis));
          String strLine;
          //Read File Line By Line
          while ((strLine = br.readLine()) != null)      {
          // Print the content on the console
              System.out.println (strLine);
          //Close the input stream
          dis.close();
          } catch (MalformedURLException mue) {
             System.out.println("Ouch - a MalformedURLException happened.");
             mue.printStackTrace();
             System.exit(1);
          } catch (IOException ioe) {
             System.out.println("Oops- an IOException happened.");
             ioe.printStackTrace();
             System.exit(1);
          } finally {
             try {
                is.close();
             } catch (IOException ioe) {
    }However, it generated the following message when run behind the firewall:
    cd C:\Documents and Settings\abc\DnldURL\build\classes
    java -cp . DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:139)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:402)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:618)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:306)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:267)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:320)
    at sun.net.www.http.HttpClient.New(HttpClient.java:315)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:510)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:487)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:615) at java.net.URL.openStream(URL.java:913) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    I have also tried the command without much luck either:
    java -cp . -Dhttp.proxyHost=wwwproxy -Dhttp.proxyPort=80 DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.io.IOException: Server returned HTTP response code: 407 for URL: http://www.yahoo.com.au/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245) at java.net.URL.openStream(URL.java:1009) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    All outgoing traffic needs to use the proxy wwwproxy (alias to http://proxypac/proxy.pac) on port 80, where it will prompt for valid authentication before allowing to get through.
    There is no problem pinging www.yahoo.com from this system.
    I am running jdk1.6.0_03, Netbeans 6.0 on Windows XP platform.
    I have tried Greg Sporar's Blog on setting the JVM option in Sun Java System Application Server (GlassFish) and
    Java Control Panel - Use browser settings without success.
    Thanks,
    George

    Hi All,
    How to set proxy authentication using java properties on the command line, or in Netbeans (Project => Properties
    => Run => Arguments). Below is a simple URL data extract program which works in absence of firewall:
    import java.io.*;
    import java.net.*;
    public class DnldURLWithoutUsingProxy {
       public static void main (String[] args) {
          URL u;
          InputStream is = null;
          DataInputStream dis;
          String s;
          try {
              u = new URL("http://www.yahoo.com.au/index.html");
             is = u.openStream();         // throws an IOException
             dis = new DataInputStream(new BufferedInputStream(is));
             BufferedReader br = new BufferedReader(new InputStreamReader(dis));
          String strLine;
          //Read File Line By Line
          while ((strLine = br.readLine()) != null)      {
          // Print the content on the console
              System.out.println (strLine);
          //Close the input stream
          dis.close();
          } catch (MalformedURLException mue) {
             System.out.println("Ouch - a MalformedURLException happened.");
             mue.printStackTrace();
             System.exit(1);
          } catch (IOException ioe) {
             System.out.println("Oops- an IOException happened.");
             ioe.printStackTrace();
             System.exit(1);
          } finally {
             try {
                is.close();
             } catch (IOException ioe) {
    }However, it generated the following message when run behind the firewall:
    cd C:\Documents and Settings\abc\DnldURL\build\classes
    java -cp . DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:139)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:402)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:618)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:306)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:267)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:320)
    at sun.net.www.http.HttpClient.New(HttpClient.java:315)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:510)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:487)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:615) at java.net.URL.openStream(URL.java:913) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    I have also tried the command without much luck either:
    java -cp . -Dhttp.proxyHost=wwwproxy -Dhttp.proxyPort=80 DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.io.IOException: Server returned HTTP response code: 407 for URL: http://www.yahoo.com.au/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245) at java.net.URL.openStream(URL.java:1009) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    All outgoing traffic needs to use the proxy wwwproxy (alias to http://proxypac/proxy.pac) on port 80, where it will prompt for valid authentication before allowing to get through.
    There is no problem pinging www.yahoo.com from this system.
    I am running jdk1.6.0_03, Netbeans 6.0 on Windows XP platform.
    I have tried Greg Sporar's Blog on setting the JVM option in Sun Java System Application Server (GlassFish) and
    Java Control Panel - Use browser settings without success.
    Thanks,
    George

  • How to set environment variables in WL ?

    Hi,
    How to set environment variables in WL ?
    Thanks,
    Srivi

    Hi,
    You can set the environmet variable in Weblogic by using the below commands
    setWLSEnv.cmd/sh ==>Set the CLASSPATH to include the WebLogic Server classes.
    Overview of WebLogic Server Domains
    or you can use to set the Environment variable along with domain specific varables using the SetDomainEnv.cmd
    To run SetDomainEnv.sh in Linux please use
    . ./setDomainEnv.sh it require two dots (Dont miss it )
    http://docs.oracle.com/cd/E28280_01/web.1111/e13749/weblogicserver.htm#ADMRF205
    Hope it helps

  • How to set environment variable ORACLE_HOME ?

    Hi
    I trying to install SAP Solution manager 4.0 SR3:
    OS: Linux RHEL4u4
    DB: Oracle
    SAPinst now stops the installation.
    To proceed with the installation, install the Oracle database as follows:
    1.Log in as user orassm.
    2.Set the DISPLAY variable.
    3.Change to directory /oracle/stage/102_32/database/SAP.
    4.Start './RUNINSTALLER'.
    After you installed the Oracle database software, proceed with the database instance
    installation by choosing 'OK' in this dialog box.
    ./RUNINSTALLER
    oracle_stage is not set (OK)
    oracle_base is not set (OK)
    oracle_home is not set (OK)
    oracle_sid is not set (OK)
    oracle_home_name is not set (OK)
    oracle_inst_group is not set (OK)
    from_location is not set (OK)
    tmp_netca_file is not set (OK)
    tmp_dbca_file is not set (OK)
    Working in /oracle/stage/102_32/database/SAP ...
    The environment variable ORACLE_HOME is not set! abort ...
    How to set environment variable ORACLE_HOME ?
    Regards
    Eric

    i
    Switch shell to bash:
    orassm:x:502:503:SAP Database Administrator:/oracle/SSM:/bin/bash
    [root@csp-p-sm00 ~]# su - orassm
    [orassm@csp-p-sm00 ~]$
    But when try to run ./RUNINSTALL
    [orassm@csp-p-sm00 SAP]$ ./RUNINSTALLER
    oracle_stage is not set (OK)
    oracle_base is not set (OK)
    oracle_home is not set (OK)
    oracle_sid is not set (OK)
    oracle_home_name is not set (OK)
    oracle_inst_group is not set (OK)
    from_location is not set (OK)
    tmp_netca_file is not set (OK)
    tmp_dbca_file is not set (OK)
    Working in /oracle/stage/102_32/database/SAP ...
    The environment variable ORACLE_HOME is not set! abort ...
    Additionaly I've post csh.cshrc and csh.login
    /etc/cshrc
    csh configuration for all shell invocations.
    by default, we want this to get set.
    Even for non-interactive, non-login shells.
    [ "`id -gn`" = "`id -un`" -a `id -u` -gt 99 ]
    if $status then
            umask 022
    else
            umask 002
    endif
    if ($?prompt) then
      if ($?tcsh) then
        set prompt='[%n@%m %c]$ '
      else
        set prompt=\[`id -nu`@`hostname -s`\]\$\
      endif
    endif
    if ( $?tcsh ) then
            bindkey "^[[3~" delete-char
    endif
    setenv MAIL "/var/spool/mail/$USER"
    limit coredumpsize 0
    if ( -d /etc/profile.d ) then
            set nonomatch
            foreach i ( /etc/profile.d/*.csh )
                    if ( -r $i ) then
                            source $i
                    endif
            end
            unset i nonomatch
    endif
    /etc/csh.login
    System wide environment and startup programs, for login setup
    if ($?PATH) then
            if ( "$" !~ /usr/X11R6/bin ) then
                    setenv PATH "$:/usr/X11R6/bin"
            endif
    else
            if ( $uid == 0 ) then
                    setenv PATH "/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin"
            else
                    setenv PATH "/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin"
            endif
    endif
    setenv HOSTNAME `/bin/hostname`
    set history=1000
    if ( ! -f $HOME/.inputrc ) then
            setenv INPUTRC /etc/inputrc
    endif
    Regards
    Eric

  • How to read system eventlog using java program in windows?

    How to read system eventlog using java program in windows?
    is there any java class available to do this ? or any one having sample code for this?
    Your friend Zoe

    Hi,
    There is no java class for reading event log in windows, so we can do one thing we can use windows system 32 VBS script to read the system log .
    The output of this command can be read using java program....
    we can use java exec for executing this system32 vbs script.
    use the below program and pass the command "eventquery"
    plz refer cscript,wscript
    import java.io.*;
    public class CmdExec {
    public static void main(String argv[]) {
    try {
    String line;
    Process p = Runtime.getRuntime().exec("Command");
    BufferedReader input =
    new BufferedReader
    (new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
    System.out.println(line);
    input.close();
    catch (Exception err) {
    err.printStackTrace();
    This sample program will list all the system log information....
    Zoe

  • How to read system evenlog using java program in windows

    How to read system evenlog using java program in windows???
    is there any java class available to do this ? or any one having sample code for this?
    Your friend Zoe

    Welcome to the Sun forums.
    >
    How to read system evenlog using java program in windows???>
    JNI. (No.)
    >
    is there any java class available to do this ? or any one having sample code for this?>You will generally get better help around here if you read the documentation, try some sample code and come back with a specific question (hopefully with an SSCCE included).
    >
    Your friend Zoe>(raised eyebrow) Thank you for sharing that with us.
    Note also that one '?' denotes a question, while 2 or more generally denotes a dweeb.

  • How to uncompress zip files using java program

    hai,
    please give some sample code to decompress the zip file.
    how to uncompress zip files using java program
    thanking you
    arivarasu

    http://developer.java.sun.com/developer/technicalArticles/Programming/PerfTuning/
    Scroll down to 'Compression'

  • How to Set Environment Variables in Windows

    Hi Guys,
    You know that we can retrieve the environment variables using System.getProperty("JAVA_HOME"); like this. It is easy.
    Can anyone tell me how to create an environment variable using System class or is there any alternate java API to create environment variable. Please let me know.
    My requirement is that I want to create the environment variable as follows
    DEV_HOME
    D:/Java/DEV

    Are you talking about Java System properties (get and set through System.get/setProperty) or Environment Variables (read-only, get through System.getenv)?
    You can set the former, not the latter (unless you start a new process through Runtime.exec(), for which you can specify a custom environment.

  • Unable to access value in System Environment Variable using Java

    I am using Java code to get the value of a System Environment Variable using the Runtime, Process java classes.
    The code works fine in tomcat, but when deployed in 9ias the code is unable to retrieve the value stored in the System environment variable in Windows 2000.

    Thanks for the comment steve, here is the code which i am using.
         public String getEnvironmentVariable()
                   // This will get the FEDREP_HOME environment variable
                   String FEDREP_HOME = null;
                   Process p = null;
                   Runtime rt = Runtime.getRuntime();
                        try {
                             // invokes a shell-command to retrieve FEDREP_HOME variable
                             String OS = System.getProperty("os.name").toLowerCase();
                                  // Get the Windows 95 environment variable
                                  if (OS.indexOf("windows 9") > -1)
                                            p = rt.exec( "command.com /c echo %FEDREP_HOME%" );
                                  // Get the Windows NT environment variable
                                  else if (OS.indexOf("nt") > -1)
                                            p = rt.exec( "cmd.exe /c echo %FEDREP_HOME%" );
                                  // Get the Windows 2000 environment variable
                                  else if (OS.indexOf("2000") > -1)
                                            p = rt.exec( "cmd.exe /c echo %FEDREP_HOME%" );
                                  // Get the Windows XP environment variable
                                  else if (OS.indexOf("xp") > -1)
                                            p = rt.exec( "cmd.exe /c echo %FEDREP_HOME%" );
                                  // Get the unix environment variable
                                  else if (OS.indexOf("linux") > -1)
                                            p = rt.exec( "sh -c echo $FEDREP_HOME" );
                                  // Get the unix environment variable
                                  else if (OS.indexOf("unix") > -1)
                                            p = rt.exec( "sh -c echo $FEDREP_HOME" );
                                  // Get the unix environment variable
                                  else if (OS.indexOf("sunos") > -1)
                                            p = rt.exec( "sh -c echo $FEDREP_HOME" );
                                  } else
                                            System.out.println("OS not known: " + OS);
                             // set up to read subprogram output
                             InputStream is = p.getInputStream();
                             InputStreamReader isr = new InputStreamReader(is);
                             BufferedReader br = new BufferedReader(isr);
                             // read output from subprogram
                             FEDREP_HOME = br.readLine();
                             br.close();
                        } catch(Exception ex)
                                  System.out.println("Error when getting FEDREP_HOME environment variable");
                                  ex.printStackTrace();
              return(FEDREP_HOME);

  • Set system classpath using java program??

    Hi,
    I want to set the System classpath using java program. Can somebody please tell how to do this.
    Prashant

    but this will set the classpath for that particular JVM only.
    Isn't it??? I want that of SYSTEM so that user can access that class path from any JVM instance.
    Prashant

  • How to set ENV variable using user profile in solaris 10 while using ssh

    Hi,
    Please help me in setting the environment variable using user profile file while using ssh method of connection (Can I use the same ~/.profile file?)
    when i am logging in using the telnet, the environment variable is automattically set, but not when I am using SSH.
    Thanks in advance
    ushas symon

    Please list your .profile and a ls -la of your home directory.
    also list the result of env after your logged through telnet and ssh.
    There should be no difference - it depends mostly on your login shell which startup script it executes. ksh uses .profile, bash: bash_profile then .profile.

  • How to set Environment variables........???

    I installed j2sdk in my system.....
    i want to know how to set env variables...?

    Which ones, what for? Did you check whether some are already set?
    Forget about the classpath variable, if you want to add that. Use the command-line arguments.
    And which OS?

  • How to open specific port using java program

    Hello,
    I want to open ,close port using java comm.plz help me how can i do it.is it possible
    by using java program.later i want to use that specific port to accept the server socket connection .plz
    help me.

    i try this java program.*but it get block in accept method*.tht mean i m not able to make connection with port.
    import java.sql.SQLException;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    class MakeConn
         public final static int PORT = 7788;
    public static java.net.Socket clientSocket = null;
    public static java.io.PrintWriter pw = null; // socket output stream
    public static java.io.BufferedReader br = null;
    public static ServerSocket server_socket;
         public static void main(String[] args) throws SQLException
         try {
              server_socket = new ServerSocket(PORT);
    clientSocket = server_socket.accept();
    System.out.println("CLIENT>>>" + clientSocket);
         br = new java.io.BufferedReader(new java.io.InputStreamReader(clientSocket.getInputStream()));
    pw = new java.io.PrintWriter(clientSocket.getOutputStream(), true);
    String message = br.readLine().trim();
    System.out.println("message is"+message);
    pw.close(); // close everything
    br.close();
    clientSocket.close();
         catch (Exception ex) {
    ex.printStackTrace();
    }

Maybe you are looking for