junior_developer181
junior_developer181

Reputation: 105

How can I execute CMD commands with java?

I want my java program to do the following things:

Access cmd and execute the commands: "d:", "cd D:\Java Projects\imageProject", "screenshot-cmd"

I tried to google that and found some code examples but none of them worked because I probably have no idea what i'm doing.

This is what I have now:

static void imageFromCMD(){
     ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "d:", "cd D:\\Java Projects\\imageProject",
                "screenshot-cmd");
     Process p = builder.start(); 
}

that code doesn't fail but i'm not getting the output (image in the dir) that i expect

I guess I'm missing the "sending" part, but how exactly can I do it?

Upvotes: 2

Views: 225

Answers (3)

Luan Pham
Luan Pham

Reputation: 76

Here is my program to check the Java version. Hope this help.

import java.io.*; 
public class RunCMDByJava {
    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "java -version");
        pb.redirectErrorStream(true);
        Process p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = br.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
        }
    }
}

Upvotes: 1

speedogoo
speedogoo

Reputation: 2848

First find out the exact cmd.exe line to run and then stuff it into a ProcessBuilder, like this

new ProcessBuilder("cmd.exe", "/c", "cd /tmp & dir")

Please note that all commands should be passed to cmd.exe as one single argument.

Upvotes: 0

Trash Can
Trash Can

Reputation: 6814

Can you try this?

ProcessBuilder processBuilder = new ProcessBuilder();
Path workingDir = Paths.get("D:\\Java Projects\\imageProject");
processBuilder.directory(workingDir.toFile()); // Edited here
processBuilder.command(".\\screenshot-cmd");
try {
    processBuilder.start();
} catch (Exception ex) {
    ex.printStackTrace();
}

An alternative option is to give the full path to the executable like so when creating a ProcessBuilder

ProcessBuilder processBuilder = new ProcessBuilder("D:\\Java Projects\\imageProject\\screenshot-cmd");
try {
    processBuilder.start();
} catch (Exception ex) {
    ex.printStackTrace();
}

One thing to note is that if you don't set the working directory when creating a ProcessBuilder, the directory of your main process is the working directory by default (basically from where your main class is being invoked), maybe try looking in there to see if the screenshots are being saved to that location

Upvotes: 2

Related Questions