我想用java代码与linux终端通信。我想存储输出并使用它。我按照给定链接中的说明实现了下面的代码。
我期望完整的终端输出帮助。但是无论是标准命令,还是蚊子命令,我都没有从输入流中得到任何东西。错误在哪里?或者你应该完全不同地做吗?
stackoverflow链接:如何在终端从java程序运行命令?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LinuxInputStream
{
public static void main(String[] args)
{
// Linux Terminal
String prefix = "/bin/bash";
String terminalCommand = "help";
String mosquittoCommand = "mosquitto --help";
ProcessBuilder pb1 = new ProcessBuilder(
new String[] {prefix, terminalCommand});
ProcessBuilder pb2 = new ProcessBuilder(
new String[] {prefix, mosquittoCommand});
try
{
executeCommand(pb1);
}
catch (IOException e)
{
System.out.println("IO Error in Terminal Command execution!");
e.printStackTrace();
}
try
{
executeCommand(pb2);
}
catch (IOException e)
{
System.out.println("IO Error in Mosquitto Command execution!");
e.printStackTrace();
}
}
private static void executeCommand(ProcessBuilder pb) throws IOException
{
Process terminalCommandProcess = pb.start();
InputStream inputStream = terminalCommandProcess.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(inputStream));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
System.out.println("Line: " + line);
i++;
}
if (i == 0) System.out.println("Nothing read from input stream");
}
}
输出:
无从输入流读取
无从输入流读取
刚刚在帖子后立即找到了解决方案:缺少“-c”部分。正确的代码片段是:
// Linux Terminal
String prefix = "/bin/bash";
String c = "-c";
String terminalCommand = "help";
String mosquittoCommand = "mosquitto --help";
ProcessBuilder pb1 = new ProcessBuilder(
new String[] {prefix, c, terminalCommand});
ProcessBuilder pb2 = new ProcessBuilder(
new String[] {prefix, c, mosquittoCommand});