【问题标题】:Why can't "chgport.exe" be found by Runtime.getRuntime().exec() in Java?为什么 Java 中的 Runtime.getRuntime().exec() 找不到“chgport.exe”?
【发布时间】:2018-10-25 19:35:00
【问题描述】:

在 Java 中,我尝试运行:
Process p = Runtime.getRuntime().exec("C:\\Windows\\System32\\chgport.exe");
还有
Process p = Runtime.getRuntime().exec("chgport.exe");

但得到以下异常:

java.io.IOException: Cannot run program "C:\Windows\System32\chgport.exe": CreateProcess error=2, 系统找不到指定的文件

我正在使用 NetBeans IDE,它使用管理员凭据运行。

【问题讨论】:

  • 根据docs.oracle.com/javase/7/docs/api/java/lang/…,exec 不需要绝对/相对路径,而是命令
  • @dnsiv 我也试过不使用路径,但得到同样的错误。
  • 你尝试过这样的事情吗? String[] cmdArray = new String[]{"C:\Windows\System32\chgport.exe"}; Runtime.exec(cmdArray);
  • @dnsiv 是的。使用“mspaint.exe”可以正常工作。更改为“chgport.exe”,然后找不到“chgport.exe”。我的 IDE 以管理员身份运行,并且“chgport.exe”无论如何都可以由用户执行。 “chgport.exe”文件有“一些东西”(而且似乎不是权限)。

标签: java windows


【解决方案1】:

我试过你的代码,它工作正常,试试这样:

String[] command = {"chgport"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.directory(new File("C:/Windows/System32/"));
pb.redirectErrorStream(true);
Process p = pb.start();

我在 Eclipse 中尝试了这两种方法,并且都运行良好 您是否有可能没有以管理员权限运行 IDE?
可以尝试关闭IDE并右键以管理员身份运行吗?

    try {
        Process p = Runtime.getRuntime().exec("C:\\Windows\\System32\\mspaint.exe");
        p.waitFor();

        String[] command = {"mspaint"};
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.directory(new File("C:/Windows/System32/"));
        pb.redirectErrorStream(true);
        Process p2 = pb.start();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

【讨论】:

  • "mspaint.exe" 是一个很好的例子,可以帮助我解决这个问题,但我还没有。我的 IDE 以管理员身份运行,并且“chgport”无论如何都可以由用户执行,所以我不知道。这很奇怪。
【解决方案2】:

您可以使用CMD /C 运行它,它“执行字符串指定的命令然后终止”。

Process p = Runtime.getRuntime().exec("CMD /C chgport.exe");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2011-01-07
    相关资源
    最近更新 更多