在使用IntelliJ Idea中执行命令时出现错误,使用ProcessBuilder。

huangapple go评论77阅读模式
英文:

Getting error in executing commands using ProcessBuilder in IntelliJ Idea

问题

IDE使用:IntelliJ
系统操作系统:Windows
尝试的命令:ProcessBuilder,Runtime.exec()

我正在执行Main.java文件(如下所示)。在终端中它可以完美运行,但在IntelliJ中会抛出以下错误。无论是使用ProcessBuilder还是Runtime.exec()都会出现相同的情况。

"C:\Program Files\Java\jdk1.8.0_241\bin\java.exe"
Exception in thread "main" java.io.IOException: Cannot run program "echo":CreateProcess error=2,系统找不到指定的文件。
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
	at TestSample.Main.main(Main.java:24)
Caused by: java.io.IOException: CreateProcess error=2,系统找不到指定的文件。
	at java.lang.ProcessImpl.create(Native Method)
	at java.lang.ProcessImpl.<init>(ProcessImpl.java:444)
	at java.lang.ProcessImpl.start(ProcessImpl.java:140)
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
	... 1 more

Process finished with exit code 1

为什么会发生这种情况?有人能帮我解决这个问题吗?

Main.java

```
public static void main(String[] args) throws InterruptedException,IOException{

    ProcessBuilder builder = new ProcessBuilder("echo", "This is ProcessBuilder Example");
    Process p=builder.start();
    int errcode = p.waitFor();
    System.out.println("程序是否成功执行?" + (errcode == 0 ? "否" : "是"));
    System.out.println("Echo输出:\n" + output(p.getInputStream()));

}
private static String output(InputStream inputStream) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + System.getProperty("line.separator"));
        }
    } finally {
        br.close();
    }
    return sb.toString();
}
此代码来源于https://examples.javacodegeeks.com/core-java/lang/processbuilder/java-lang-processbuilder-example/

<details>
<summary>英文:</summary>

IDE used: IntelliJ &lt;br&gt;
System OS: Windows &lt;br&gt;
Commands tried: ProcessBuilder, Runtime.exec()

I am executing &lt;a href=&quot;#JavaFile&quot;&gt;Main.java&lt;/a&gt; file (mentioned below). It executes perfectly in terminal but in IntelliJ, it throws the following error. The same happens with both ProcessBuilder and Runtime.exec().&lt;br&gt;

"C:\Program Files\Java\jdk1.8.0_241\bin\java.exe"
Exception in thread "main" java.io.IOException: Cannot run program "echo": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at TestSample.Main.main(Main.java:24)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:444)
at java.lang.ProcessImpl.start(ProcessImpl.java:140)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 1 more

Process finished with exit code 1

Why is it happening? Can someone help me resolve this issue? &lt;br&gt;

&lt;h2 id=&quot;JavaFile&quot;&gt;&lt;b&gt;Main.java&lt;/b&gt;&lt;/h2&gt;
public static void main(String[] args) throws InterruptedException,IOException{

    ProcessBuilder builder = new ProcessBuilder(&quot;echo&quot;, &quot;This is ProcessBuilder Example&quot;);
    Process p=builder.start();
    int errcode = p.waitFor();
    System.out.println(&quot;Program is executed successfully?&quot;+(errcode == 0 ?&quot;No&quot;:&quot;Yes&quot;));
    System.out.println(&quot;Echo Output:\n&quot; + output(p.getInputStream()));

}
private static String output(InputStream inputStream) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + System.getProperty(&quot;line.separator&quot;));
        }
    } finally {
        br.close();
    }
    return sb.toString();
}
This code is retrieved from https://examples.javacodegeeks.com/core-java/lang/processbuilder/java-lang-processbuilder-example/

</details>


# 答案1
**得分**: 3

`echo` 不是一个有效的可执行文件,而是由命令行 shell (`cmd.exe`) 提供的命令。

为了从其他进程中运行这个命令,您需要启动 `cmd.exe` 并将参数传递给它。

在 Windows 中,正常工作的代码如下所示:

```java
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "echo", "This is ProcessBuilder Example from JCG");

对于其他操作系统,您需要将 cmd.exe 替换为 /bin/bash 等。

英文:

echo is not a valid executable, instead it's a command provided by the command line shell (cmd.exe).

In order to run this command from the other processes you have to start cmd.exe and pass the arguments to it.

The working code for Windows would look like this:

ProcessBuilder pb = new ProcessBuilder(&quot;cmd.exe&quot;, &quot;/C&quot;, &quot;echo&quot;, &quot;This is ProcessBuilder Example from JCG&quot;);

For other operating systems you would need to replace cmd.exe with /bin/bash, etc.

huangapple
  • 本文由 发表于 2020年4月11日 07:06:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/61149956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定