英文:
ProcessBuilder working in Linux but not Windows
问题
这是一个运行echo
命令的简单程序,使用ProcessBuilder
,在我的Linux机器上运行良好,但在Windows上运行时会抛出IOException
异常。
这是我的程序的简化版本。它将echo
和hello
作为ProcessBuilder
的参数,然后将输出保存到一个字符串中并打印输出。在Linux上,输出是hello
,而在Windows上会捕获IOException
。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestPB {
public static void main(String[] args) throws InterruptedException {
ProcessBuilder pb = new ProcessBuilder("echo", "hello");
try {
Process process = pb.start();
BufferedReader readProcessOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
String line = "";
while ((line = readProcessOutput.readLine()) != null) {
output += line;
output += System.getProperty("line.separator");
}
process.waitFor();
if (output.length() > 0) {
System.out.println(output.substring(0, output.length() - 1));
} else {
System.out.println("No result");
}
} catch (IOException io) {
System.out.println("IOException thrown");
}
}
}
有谁知道为什么在Windows上不起作用吗?
英文:
I have a simple program that runs the echo
command with ProcessBuilder
, and the program works perfectly fine on my Linux machine, but it throws an IOException
when running on Windows.
This is a simplified version of my program. It takes echo
and hello
as arguments for ProcessBuilder
, and then saves the output into a string and prints the output. In Linux, the output is hello
, and in Windows an IOException
is caught.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestPB {
public static void main(String[] args) throws InterruptedException {
ProcessBuilder pb = new ProcessBuilder("echo", "hello");
try {
Process process = pb.start();
BufferedReader readProcessOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = "";
String line = "";
while ( (line = readProcessOutput.readLine()) != null) {
output += line;
output += System.getProperty("line.separator");
}
process.waitFor();
if(output.length() > 0) {
System.out.println(output.substring(0, output.length() -1));
} else {
System.out.println("No result");
}
} catch (IOException io) {
System.out.println("IOException thrown");
}
}
}
Does anyone know why this is not working in Windows?
答案1
得分: 3
echo
在Windows上不是一个程序,而是一个内部的shell命令<sup>*</sup>,因此您需要调用命令行解释器:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "echo", "hello");
<sup>*) 参考:维基百科</sup>
英文:
echo
is not a program on Windows, it's an internal shell command<sup>*</sup>, so you need to invoke the command-line interpreter:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "echo", "hello");
<sup>*) Reference: Wikipedia</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论