We help IT Professionals succeed at work.

Working with command line commands in Java

LordSM
LordSM asked
on
Medium Priority
1,948 Views
Last Modified: 2013-11-23
Hi

I am trying to make a small Java app with a GUI for which I am using Netbeans. My app will present a GUI where user can fill in some values. These values will be arguments to certain command line executable commands. I basically have some commands which will do some modification/ copying files here and there with destination being specified in the GUI form. How do I run commands in Java. I am using this to run a copy command.


It will be awesome, if you can give me some overview on where I can find help on it, Like some tutorial or something on how to work with command line in Java. I get errors in illegal unicode, escape characters and unable to find commands. I am going to run these on an IIS server, mostly Win2K3
Comment
Watch Question

Dejan PažinHead of SW Development

Commented:

A nice tutorial on that:

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

Author

Commented:
I have been trying to do this, but am not able to copy a file from one directory to another

try
         {
             Runtime rt =Runtime.getRuntime();
//This will lauch IE and this program will end
//String s = "C:\\Program Files\\Internet Explorer\\iexplore.exe \"http://www.mapinfo.com\" ";
//Process p =rt.exec(s);
            // Runtime.getRuntime().exec("explorer.exe");
//Runtime rt= Runtime.getRuntime();
//--------------------------------
//String[] cmd = new String[2];
//cmd[0] = "explorer.exe";
//cmd[1] = "c:";
//cmd[2] = "util";
//--------------------------------
String[] cmd = new String[4];
cmd[0] = "cmd.exe";
cmd[1] = "copy";
cmd[2] = "c:\\XMLFileCopy.xml";
cmd[3] = "c:\\AOE2CONQ";

//cmd[1]= "C:/BigTest.txt";

//copy c:\XMLFileCopy.xml  "c:\WINNT"
//--------------------------------
rt.exec(cmd);
System.out.println("Got it");
         }

catch (Exception ex)
{

    ex.printStackTrace();
}

Please tell, if there are any bugs in this one
Dejan PažinHead of SW Development

Commented:

This will work:

public class CopyTest {
    public static void main(String[] args) {
        try {
            Runtime rt = Runtime.getRuntime();
            String[] cmd = new String[3];
            cmd[0] = "cmd.exe";
            cmd[1]="/C";
            cmd[2] ="copy c:\\XMLFileCopy.xml c:\\AOE2CONQ";
            rt.exec(cmd);
            System.out.println("Got it");
        }

        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Author

Commented:
for curiosity sake, what does this mean - cmd[1]="/C";

Author

Commented:
it gives java.lang.NullPointerException
Dejan PažinHead of SW Development
Commented:

It means:  - Carry out command and then terminate
See description of options here:
http://www.ss64.com/nt/cmd.html

Where do you get NPE? I need to see the exact code you are running. The code I sent surely doesnt give NPE, I tested it.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:

I am trying to run a command to add a group name. It is executed in command prompt of Windows 2003/2000
Say this is the command I want to execute:
net localgroup LordSM /add
Here LordSM is the group name.

I wrote the following code but it does not seem to work. Please suggest.

String ABC=Value1TextField.getText();
Value2Label.setText("Value is now " + ABC);

// Above is to get value from a JText Field

// Below is the code to run command for adding a group name to a System.
 String ExecutedCmd = "net localgroup " + ABC + "/add";
    Process p = Runtime.getRuntime().exec(ExecutedCmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
           
    // read the output from the command
           
     System.out.println("Here is the standard output of the command:\n");
     while ((s = stdInput.readLine()) != null)
     {                System.out.println(s);             }
           
    // read any errors from the attempted command

      System.out.println("Here is the standard error of the command (if any):\n");
      while ((s = stdError.readLine()) != null)
      {       System.out.println(s);           }
           
   

Author

Commented:
I am trying to run a command to add a group name. It is executed in command prompt of Windows 2003/2000
Say this is the command I want to execute:
net localgroup LordSM /add
Here LordSM is the group name.

I wrote the following code but it does not seem to work. Please suggest.

String ABC=Value1TextField.getText();
Value2Label.setText("Value is now " + ABC);

// Above is to get value from a JText Field

// Below is the code to run command for adding a group name to a System.
String ExecutedCmd = "net localgroup " + ABC + "/add";
Process p = Runtime.getRuntime().exec(ExecutedCmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));


// read the output from the command

System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{ System.out.println(s); }

// read any errors from the attempted command

System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
{ System.out.println(s); }

-----


I am trying to run a command to add a group name. It is executed in command prompt of Windows 2003/2000
Say this is the command I want to execute:
net localgroup LordSM /add
Here LordSM is the group name.

I wrote the following code but it does not seem to work. Please suggest.

String ABC=Value1TextField.getText();
Value2Label.setText("Value is now " + ABC);

// Above is to get value from a JText Field

// Below is the code to run command for adding a group name to a System.
String ExecutedCmd = "net localgroup " + ABC + "/add";
Process p = Runtime.getRuntime().exec(ExecutedCmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));


// read the output from the command

System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{ System.out.println(s); }

// read any errors from the attempted command

System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
{ System.out.println(s); }


It does not seem to work means, that no Standard Error is defined, when it executes and group name is not added as well. The following is JUnit Test Result: Hope it gives a better idea of the problem I am facing:

compile:
run:
Here is the standard output of the command:

Here is the standard error of the command (if any):

The syntax of this command is:



NET LOCALGROUP [groupname [/COMMENT:"text"]] [/DOMAIN]
groupname {/ADD [/COMMENT:"text"] | /DELETE} [/DOMAIN]
groupname name [...] {/ADD | /DELETE} [/DOMAIN]

Got it
BUILD SUCCESSFUL (total time: 10 minutes 49 seconds)

----------------

I had even tried this:
Runtime rt =Runtime.getRuntime();
String[] cmd = new String[3];
cmd[0] = "cmd.exe";
cmd[1]="net localgroup";
cmd[2] =ABC + "/add";
rt.exec(cmd);

but again, it does not give any error as such, but it does not create the group name either. Please suggest. We can see the group names that are added on right clicking My Computer Icon and click Manage and then go to User & Group section. On executing either of the code nothing happens.

Thanks
Commented:
I see a missing interval for starters
String ExecutedCmd = "net localgroup " + ABC + "/add";
should be
String ExecutedCmd = "net localgroup " + ABC + " /add";

This of course if you are sure that
net localgroup LordSM /add
works. :)

For the small example I also see the missing space:
Runtime rt =Runtime.getRuntime();
String[] cmd = new String[3];
cmd[0] = "cmd.exe";
cmd[1]="net localgroup";
cmd[2] =ABC + " /add"; //added a space
rt.exec(cmd);
java.lang.Runtime.exec(ExecutedCmd);

Commented:
ahoffmann,

What is this now? He knows which method to use. AND exec is not a static method so your line won't even work.
So any reason for posting this here? It does not add anything to the discussion and is not a correct syntax in java

Author

Commented:
Well, guys thanks for all the help. There are multitude of command lines, that I have to execute. And I think Java might not be the best choice for it all. I figured it out in VB Script. And for GUI part of it I wrapped it as an .hta file (new stuff, I learned) that makes simple, light executable for my work. Thanks a lot Ahoffman and Venabili

LordSM
Venabili, you're right. Seems that I grepped my to ancient sources, sorry.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.