Rumah  >  Artikel  >  Java  >  ProcessBuilder vs Runtime.exec(): Mengapa Mereka Berkelakuan Berbeza Apabila Melaksanakan Perintah Luaran?

ProcessBuilder vs Runtime.exec(): Mengapa Mereka Berkelakuan Berbeza Apabila Melaksanakan Perintah Luaran?

Barbara Streisand
Barbara Streisandasal
2024-11-15 02:54:02766semak imbas

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");

Alternatively, a List can be used:

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

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

Atas ialah kandungan terperinci ProcessBuilder vs Runtime.exec(): Mengapa Mereka Berkelakuan Berbeza Apabila Melaksanakan Perintah Luaran?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn