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

4 Answers 4

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();
Sign up to request clarification or add additional context in comments.

Comments

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();        
    }
}

2 Comments

you used {"CMD", "/C", "dir"}. Does cmd stands for command, /C denotes C directory and dir means any directory in the C ?
Check javadoc for ProcessBuilder constructor, index 0 is the program and remaining indexes are it's arguments.
0

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

Comments

0

This is used to run commmand line commands using Java

      Runtime.getRuntime().exec()

1 Comment

This will give you a lot of information regardin how to use this class programmingforums.org/post208741.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.