2

I want to ask we can run commands in windows like i open the command prompt by typing cmd. C:/> cd programFiles C:/>cd anydir

I want to ask can i run these commands from java. Like i want to run the command cd programfilesthrough java. can i do it?

Thanks

Basit
  • 8,426
  • 46
  • 116
  • 196

4 Answers4

1

You can use ProcessBuilder class as follows:

public static void main(String [] args) throws IOException 
{                
    String[] command = {"CMD", "/C", "dir"};
    // ProcessBuilder will execute process named 'CMD' and will provide '/C' and 'dir' as command line arguments to 'CMD'

    ProcessBuilder pbuilder = new ProcessBuilder(command);
    Process process = probuilder.start();

    //Wait for process to finish
    try 
    {            
        int exitValue = process.waitFor();
        System.out.println("\n\nExit Value is " + exitValue);        
    } 
    catch (InterruptedException e) 
    {            
        e.printStackTrace();        
    }
}
Azodious
  • 13,752
  • 1
  • 36
  • 71
  • you used `{"CMD", "/C", "dir"}`. Does cmd stands for command, /C denotes C directory and dir means any directory in the C ? – Basit Sep 26 '12 at 07:09
  • Check javadoc for [ProcessBuilder constructor](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html#ProcessBuilder(java.util.List)), index 0 is the program and remaining indexes are it's arguments. – Azodious Sep 26 '12 at 07:21
1

Please see my answer to a similar question which some people found useful. Here is it:

You can use Runtime.exec(java.lang.String, java.lang.String[], java.io.File) where you can set the working directory.

Or else you can use ProcessBuilder as follows:

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();
Community
  • 1
  • 1
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73
0

If you want to change working directory there are built in functions for that. If you want to run commands, see example

CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
0

This is used to run commmand line commands using Java

      Runtime.getRuntime().exec()
Sanket
  • 393
  • 1
  • 3
  • 12
  • This will give you a lot of information regardin how to use this class http://www.programmingforums.org/post208741.html – Sanket Sep 26 '12 at 06:45