Java运行时.exec()不会打开可执行文件

时间:2014-06-25 10:30:21

标签: java

我正在尝试使用Runtime和Process

执行另一个文件
try
{
Runtime run =   Runtime.getRuntime();
Process pro =   run.exec("C:\\Users\\user\\Desktop\\file.exe");

}
catch(Exception a)
{
    a.printStackTrace();
}

我可以在run或cmd中输入此命令,并且能够打开文件,但是通过我的程序运行它将无法打开。没有错误,它只是没有打开。

4 个答案:

答案 0 :(得分:1)

你必须

Process pro =   run.exec("C:\\Users\\user\\Desktop\\file.exe",null,"C:\\Users\\user\\Desktop\\");

请参阅Run .exe file from Java from file location

答案 1 :(得分:1)

为了更好地理解正在发生的事情(并且它实际上是Process类的要求),您需要重定向流程的输入和错误流 - 并且使用ProcessBuilder是启动流程的推荐方法:

public static void main(String[] args) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("C:\\Users\\user\\Desktop\\file.exe");
    runProcess(pb)
}

private static void runProcess(ProcessBuilder pb) throws IOException {
    pb.redirectErrorStream(true);
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}

答案 2 :(得分:1)

尝试这种方式:

  String []cmdarray = new String[4];
  cmdarray[0] = "cmd";
  cmdarray[1] = "/c";
  cmdarray[2] = "start";
  cmdarray[3] = "C:\\Users\\user\\Desktop\\file.exe";
  Runtime.getRuntime().exec(cmdarray);

答案 3 :(得分:1)

尝试这个,创建一个批处理文件,如start_file.bat。 像这样的内容:

cd C:\Users\user\Desktop ----- Goto this directory
C:   ----- This line is very important
file.exe

这两种方法都运作良好。

  Runtime r  = Runtime.getRuntime();
  String []cmdarray = new String[4];
  cmdarray[0] = "cmd";
  cmdarray[1] = "/c";
  cmdarray[2] = "start";
  cmdarray[3] = "C:/users/desktop/start_file.bat";
  r.exec(cmdarray);

这一个:

  r.exec("C:/users/desktop/start_file.bat");
  You can read the output from this new process.