Execute external program in java

こ雲淡風輕ζ 提交于 2019-11-26 00:44:30

问题


I tried to make an application that calls an external program that I have to pass two parameters. It doesn\'t give any errors.The program.exe,written in c++, takes a picture and modifies the content of txt file. The java program runs but it does nothing

Here is my sample code

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

回答1:


borrowed this shamely from 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);
}

More information here

Other issues on how to pass commands here and here




回答2:


This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives




回答3:


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

Try online



来源:https://stackoverflow.com/questions/13991007/execute-external-program-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!