[java] Run cmd commands through Java

I found several code snippets for running cmd commands through a Java class, but I wasn't able to understand it.

This is code for opening the cmd

public void excCommand(String new_dir){
    Runtime rt = Runtime.getRuntime();
    try {
        rt.exec(new String[]{"cmd.exe","/c","start"});

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And I found some other links for adding other commands such as cd http://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-java

How to open the command prompt and insert commands using Java?

Can anyone help me to understand how to cd a directory such as:

 cd C:\Program Files\Flowella

then run other commands on that directory?

This question is related to java cmd cd

The answer is


Stopping and Disabling a service can be done via below code:

static void sdService() {
    String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
    try {           
        Process process = new ProcessBuilder(cmd).start();
        process.waitFor();      
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                            
        line = null;
        bufferedReader = null;
        Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
        p.waitFor();
        bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }                   
    } catch (Exception e) {
        e.printStackTrace();
    }                   
}

Enabling and Starting a service can be done via below code

static void esService() {
    String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
                    
    try {
        Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
        //Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
        p.waitFor();        
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                            
        line = null;
        bufferedReader = null;
        Process process = new ProcessBuilder(cmd).start();          
        process.waitFor();
        bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
                        
    } catch (Exception e) {
        e.printStackTrace();
    }               
}

Executing command from any folder can be done via below code.

static void runFromSpecificFolder() {       
    try {
        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
        //processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
        processBuilder.redirectErrorStream(true);
        Process p = processBuilder.start();
        p.waitFor();        
        String line = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }                
    } catch (Exception e) {
        e.printStackTrace();
    }               
}
    
public static void main(String args[]) {
    sdService();
    runFromSpecificFolder();
    esService();
}

Try this:

Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");

Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.

Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.


If you want to perform actions like cd, then use:

String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));

Example:

String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();

It is important that you split the command and all arguments in separate strings of the string array (otherwise they will not be provided correctly by the ProcessBuilder API).


You can try this:-

Process p = Runtime.getRuntime().exec(command);

My example (from real project)

folder — File.

zipFile, filesString — String;

        final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
        logger.info("Start unzipping: {}    into the folder {}", command, folder.getPath());
        final Runtime r = Runtime.getRuntime();
        final Process p = r.exec(command, null, folder);
        final int returnCode = p.waitFor();

        if (logger.isWarnEnabled()) {
            final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = is.readLine()) != null) {
                logger.warn(line);
            }
            final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = is2.readLine()) != null) {
                logger.warn(line);
            }
        }

Here is a more complete implementation of command line execution.

Usage

executeCommand("ls");

Output:

12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src

Code

private void executeCommand(String command) {
    try {
        log(command);
        Process process = Runtime.getRuntime().exec(command);
        logOutput(process.getInputStream(), "");
        logOutput(process.getErrorStream(), "Error: ");
        process.waitFor();
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

private void logOutput(InputStream inputStream, String prefix) {
    new Thread(() -> {
        Scanner scanner = new Scanner(inputStream, "UTF-8");
        while (scanner.hasNextLine()) {
            synchronized (this) {
                log(prefix + scanner.nextLine());
            }
        }
        scanner.close();
    }).start();
}

private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");

private synchronized void log(String message) {
    System.out.println(format.format(new Date()) + ": " + message);
}

The easiest way would be to use Runtime.getRuntime.exec().

For example, to get a registry value for the default browser on Windows:

String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
    Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
    e.printStackTrace();
}

Then use a Scanner to get the output of the command, if necessary.

Scanner kb = new Scanner(process.getInputStream());

Note: the \ is an escape character in a String, and must be escaped to work properly (hence the \\).


However, there is no executable called cd, because it can't be implemented in a separate process.

The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly.

Easiest way for your command:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");

public class Demo { public static void main(String args[]) throws IOException {

    Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    while (true) {
        line = in.readLine();
        if (line == null) { break; }
        System.out.println(line);
    }
}

}

You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.

To set the current working directory in your actual Java program, you should write:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");

The simplest and shortest way is to use CmdTool library.

new Cmd()
         .configuring(new WorkDir("C:/Program Files/Flowella"))
         .command("cmd.exe", "/c", "start")
         .execute();

You can find more examples here.


Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.

public class CmdCommander {

public static void main(String[] args) throws Exception {
    //easyway to start native windows command prompt from Intellij

    /*
    Rules are:
    1.baseStart must be dual start
    2.first command must not have &.
    3.subsequent commands must be prepended with &
    4.drive change needs extra &
    5.use quotes at start and end of command batch
    */
    String startQuote = "\"";
    String endQuote = "\"";
    //String baseStart_not_taking_commands = " cmd  /K start ";
    String baseStart = " cmd  /K start cmd /K ";//dual start is must

    String first_command_chcp = " chcp 1251 ";
    String dirList = " &dir ";//& in front of commands after first command means enter
    //change drive....to yours
    String changeDir = " &cd &I: ";//extra & makes changing drive happen

    String javaLaunch = " &java ";//just another command
    String javaClass = " Encodes ";//parameter for java needs no &

    String javaCommand = javaLaunch + javaClass;
    //build batch command
    String totalCommand =
            baseStart +
                    startQuote +
                    first_command_chcp +
                    //javaCommand +
                    changeDir +
                    dirList +
                    endQuote;

    System.out.println(totalCommand);//prints into Intellij terminal
    runCmd(totalCommand);
    //Thread t = Thread.currentThread();
    //t.sleep(3000);
    System.out.println("loppu hep");//prints into Intellij terminal

}


public static void runCmd(String command) throws Exception {

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);


}

}


one of the way to execute cmd from java !

public void executeCmd() {
    String anyCommand="your command";
    try {
        Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?

Examples related to cd

Change directory command in Docker? Change working directory in my current shell context when running Node script How to cd into a directory with space in the name? How do I find the current directory of a batch file, and then use it for the path? Run cmd commands through Java Equivalent of shell 'cd' command to change the working directory?