我尝试创建一个调用外部程序的应用程序,我必须传递两个参数。它没有给出任何错误。用c ++编写的program.exe拍照并修改了txt文件的内容。 java程序运行但它什么都不做
这是我的示例代码
String[] params = new String [3];
params[0] = "C:\\Users\\user\\Desktop\\program.exe";
params[1] = "C:\\Users\\user\\Desktop\\images.jpg";
params[2] = "C:\\Users\\user\\Desktop\\images2.txt";
Runtime.getRuntime().exec(params);
答案 0 :(得分:59)
从here
借来这个耻辱Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").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);
}
更多信息here
的其他问题答案 1 :(得分:14)
这是不对的。 Here's您应该如何使用Runtime.exec()
。您也可以尝试使用更现代的堂兄ProcessBuilder
:
答案 2 :(得分:0)
import java.io.*;
public class Code {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
Process process = builder.start();
StringBuilder out = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = null;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append("\n");
}
System.out.println(out);
}
}
}