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;

1 comments to "Setting windows environment variable through Java code"

Post a Comment

Whoever writes Inappropriate/Vulgar comments to context, generally want to be anonymous …So I hope U r not the one like that?
For lazy logs, u can at least use Name/URL option which doesn’t even require any sign-in, The good thing is that it can accept your lovely nick name also and the URL is not mandatory too.
Thanks for your patience
~Krishna(I love "Transparency")

Popular Posts

Enter your email address:

Buffs ...


Powered by WidgetsForFree