Home > Java > javaTutorial > body text

ProcessBuilder vs Runtime.exec(): Why Do They Behave Differently When Executing External Commands?

Barbara Streisand
Release: 2024-11-15 02:54:02
Original
769 people have browsed it

ProcessBuilder vs Runtime.exec(): Why Do They Behave Differently When Executing External Commands?

ProcessBuilder vs. Runtime.exec(): Analyzing the Discrepancies

When executing external commands in Java, one may encounter discrepancies between Runtime.getRuntime().exec(...) and new ProcessBuilder(...).start(). The following exploration aims to shed light on these differences and provide solutions to achieve consistent behavior.

Default Argument Handling

One key distinction between the two approaches lies in their handling of arguments. Runtime.getRuntime().exec() expects a single string or an array of strings, while ProcessBuilder expects an array of strings or a List of strings. When using exec() with a single string, it internally tokenizes the string to create an argument array.

ProcessBuilder Behavior

In the case of ProcessBuilder, arguments are passed as an array or list, where each element represents an argument. However, if the string is not properly tokenized, a single argument will be formed, including any spaces. This can lead to unexpected behavior, as in the example provided where the command was not executed correctly.

Solution

To resolve this issue with ProcessBuilder, ensure that the arguments are properly tokenized:

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");
Copy after login

Alternatively, a List can be used:

List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
Copy after login

By pre-tokenizing the arguments, the desired behavior can be achieved.

The above is the detailed content of ProcessBuilder vs Runtime.exec(): Why Do They Behave Differently When Executing External Commands?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template