1

I tried to run command line from Java code.

public void executeVcluto() throws IOException, InterruptedException {
    String command = "cmd /c C:\\Users\\User\\Downloads\\program.exe C:\\Users\\User\\Downloads\\file.txt 5 >> C:\\Users\\User\\Downloads\\result.txt";
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    if (process.exitValue() == 0) {
        System.out.println("Command exit successfully");
    } else {
        System.out.println("Command failed");
    }

}

However, the file where output result should be written result.txt is not created. When I execute this command from cmd on windows the file is created and the result is written in it. I get Command exit successfully message. Could someone help me?

2 Answers 2

4

output redirection is shell feature, java Process does not understand that.

Some other alternatives are 1. create a single batch file with above lines and invoke it using ProcessBuilder/Runtime 2. Use ProcessBuilder and redirect output using output streams. Example (it is for shell, will work for batch files too) is here

ProcessBuilder builder = new     ProcessBuilder("cmd", "/c", "C:\\Users\\User\\Downloads\\program.exe", "C:\\Users\\User\\Downloads\\file.txt" , "5");
builder.redirectOutput(new File("C:\\Users\\User\\Downloads\\result.txt"));
builder.redirectError(new File("C:\\Users\\User\\Downloads\\resulterr.txt"));

Process p = builder.start(); // throws IOException

(above is tweaked from Runtime's exec() method is not redirecting the output)

Sign up to request clarification or add additional context in comments.

Comments

0

Try cmd.exe, including a path, if necessary.

You're creating an entirely new process, which is different than giving a command to a shell.

Comments

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.