How to set / get windows environment variables through Java code?

How to set / get windows environment variables through Java code?

Below simple program is self explained on how to use set / get the windows environment variables.

    import java.util.*;  
    public class Test  
        public static void main(String[] args) throws Exception  
            ProcessBuilder pb = new ProcessBuilder("CMD.exe", "/C", "SET"); // SET prints out the environment variables  
            Map env = pb.environment();  
            String path = env.get("Path") + ";C:\\cygwin\\bin";  
            env.put("Path", path);  
            Process process = pb.start();  
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null)  

Read more

Setting windows environment variable through Java code

Setting windows environment variable through Java code...

The below is a simple Java class code which will pass few parameters to a method which get's validated against null and empty conditions and then a process will be started with those values.

Basically one batch script or shell script gets run depending on the OS name found from environment .. it sets two environment variables in the operating system.
import java.util.Map;

public class IfixConfig {

  * @param args
  * @param MYPRODUCT_Home
  * @param WAS_username
  * @param WAS_password
  * @param iFixLocation
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  System.out.println("Starting IFIX configuration");
  String MYPRODUCT_Home = "C:\\Program Files\\XYZ\\MYPRODUCT";
  String WAS_username = "smadmin";
  String WAS_password = "g0vmware";
  String iFixLocation = "C:\\Program Files\\XYZ\\MYPRODUCT\\ui\\ifixes\\\\0001";
  int result = ifixConfig(MYPRODUCT_Home, WAS_username, WAS_password,
  System.out.println("Result:" + result);


 private static int ifixConfig(String MYPRODUCT_Home, String wAS_username,
   String wAS_password, String iFixLocation) {
  int resultCode = -1;
  try {
   System.out.println(MYPRODUCT_Home + wAS_username + wAS_password
     + iFixLocation);
   ProcessBuilder pb = null;
   String postConfigScript = iFixLocation + "/post_install_configure.";
   if (wAS_username != null && !(wAS_username.isEmpty())
     && wAS_password != null && !(wAS_password.isEmpty())) {
    System.out.println("WAS username and passwords provided");
    if (System.getProperty("").startsWith("Windows"))
     postConfigScript = postConfigScript + "bat"; 
      pb = new ProcessBuilder("CMD.exe", "/C", postConfigScript);  
     postConfigScript = postConfigScript + "sh" ;
     pb = new ProcessBuilder(postConfigScript);
    System.out.println("Post config script:"+postConfigScript); File(iFixLocation));
    Map env = pb.environment();
    env.put("MYPRODUCT_WAS_PASSWORD", wAS_password);
    Process process = pb.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
     if ( line.equals("BUILD SUCCESSFUL")){
      resultCode = 0 ;
   } else {
    System.out.println("WAS username and password should not be empty");


  } catch (Exception e) {
  return resultCode;

Read more

Shell Script Tips -1

The below shell scripts are typical example codes which helps us to understand certain frequently used codes.

1. How to get the absolute or full path while calling another shell script from one shell script.

source $(readlink -f "") uninstall

The above code snippet calls another shell script by name which is available in the same directory of current script.
Abosolute path will be used with the readlink -f option there. uninstall isa parameter passed to it.

2. How to check how many parameters are passed in to a shell script..
if [ $# != "1" ]; then
    echo "Usage: install or uninstall"
$# represents total number of parameters passed to a shell script when called.
In the above example code if at least one parameter is not passed it throws a message and exits.

3. How to check if a variable is set or not . How to check if a viariale has empty string ?

    if [ -z $LOCALE_CODE ];
        then JAZZSM_SYSTEM_LOCALE="en_US"

In the above example snippet we are setting some value for LOCALE_CODE if in case it is not set for some reason -z option with if condition returns true
so in above example if it( if [ -z $LOCALE_CODE ] ) is true  it will set it to en_US

4. How to get the parent directory path of a file or directory ?

    PresentDir=`dirname $PWD` 

When dirname is given a pathname, it will delete any suffix beginning with the last slash ('/') character and return the result.
For example:

 $ dirname /usr/home/carpetsmoker/

5. How to get the only filename when absolute path is given ?


    $ basename /home/jsmith/

    $ basename /home/jsmith/ .wiki

    IFIX_NO=`basename $PWD`

6.     How to read a properties file in shell script  ?

    # Reading to find IM Install location
    IM_HOME=`sed '/^\#/d' $PropertiesFile | grep 'product.install.location'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
    echo IM Install Location is : $IM_HOME
    Example :
    $PropertiesFile contents are like below ..
    #Fri, 01 Mar 2013 02:59:37 -0500

    The while process is to Scan through the file to get an individual property

    This works well if you just want to read a specific property in a Java-style properties file. Here's what it does:

    * Remove comments (lines that start with '#') >> sed '/^\#/d'
    * Grep for the property >>  grep 'someproperty' 
    * Get the last value using >> tail -n 1
    * Strip off the property name and the '=' (using {{cut -d "=" -f2-}) to handle values with '=' in them).

     sed '/^\#/d' | grep 'someproperty'  | tail -n 1 | cut -d "=" -f2-

    It can also be handy to strip off the leading and trailing blanks with this sed expression:


    Which makes the whole thing look like this:

    sed '/^\#/d' | grep 'someproperty'  | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'


7.  How to check file existance before running it ?


Having quotes for the file path eliminates issues arise out of spaces in the path.

8. How to read input values through shell script ?

    # Ask for WAS credentials
    if [ -z "${JAZZSM_WAS_USERNAME}" ]
      echo -n "${wasUserNamePrompt}: "

echo -n "${wasUserNamePrompt}: "     >> it helps to prompt user with particular string before commandline prompt while running shell script, in order to resolve wasUserNamePrompt string we need to run its correspinding properties file before this call .
For example has text like below , and when it is run before the above command it will resolve this value.



wasUserNamePrompt="Enter the Websphere Application Server user name:"

wasPasswordPrompt="Enter the Websphere Application Server password:"

Read more


Enter your email address:

Buffs ...


hits counter
View My StatsCheck Google Page Rank

Add to Google Reader or Homepage

Bookmark and Share


Powered by WidgetsForFree