调用可执行文件并传递参数

我正在研究一种从 Java 调用 exe 并传入特定参数的机制。我该怎么做呢?

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;


System.out.printf("Output of running %s is:", Arrays.toString(args));


while ((line = br.readLine()) != null) {
System.out.println(line);
}

以前的代码可以工作。但我无法传递参数.Exe 接受参数。另一个问题是 PathToExe 有空格时。ProcessBuilder 似乎不起作用。例如:

C:\\User\\My applications\\MyExe.exe

谢谢你。

142300 次浏览

You're on the right track. The two constructors accept arguments, or you can specify them post-construction with ProcessBuilder#command(java.util.List) and ProcessBuilder#command(String...).

Pass your arguments in constructor itself.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
import java.io.IOException;
import java.lang.ProcessBuilder;


public class handlingexe {
public static void main(String[] args) throws IOException {
ProcessBuilder p = new ProcessBuilder();
System.out.println("Started EXE");
p.command("C:\\Users\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");


p.start();
System.out.println("Started EXE");
}
}

Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.

Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)

**

ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
int returnVal = process.exitValue();
}

**

I built a utility for the same, very basic one.

    public class CallOsExeUtil {
public static String call(String[] args) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
StringBuilder sb = new StringBuilder("");
if (waitFlag == 0) {
if (process.exitValue()==0) {
System.out.println("This is me " + process.info());


BufferedInputStream in = (BufferedInputStream) process.getInputStream();
byte[] contents = new byte[1024];


int bytesRead = 0;


while ((bytesRead = in.read(contents)) != -1) {
sb.append(new String(contents, 0, bytesRead));
}
}


}
return sb.toString();
}
}