Java运行终端命令并发送输入

时间:2019-11-14 10:33:41

标签: java

我已经设置了master password for terminal,并且我想创建一个Java程序,其中添加了一些额外的功能。为此,我需要从终端发送和接收输入/输出。我尝试了Java Program that runs commands with Linux Terminal中的建议,但没有任何运气。由于某些原因,输入未传递,如果我强制停止,则Your master password:会被打印出来(这是应该传递输入的)。下面是我的代码,任何人都可以看到我在做什么吗?

try
{
    // Send the command
    Process process = new ProcessBuilder("mpw", "-u", "Name", "-t", "l", "Website").start();
    String key = "somekey";
    OutputStream stdOutput = process.getOutputStream();
    // Send an input
    stdOutput.write(key.getBytes());
    // Store the input (and error) in a buffer
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    // Read the output from the command:
    int data;
    while ((data = stdInput.read()) != -1)
        System.out.write(data);

    while ((data = stdError.read()) != -1)
        System.out.write(data);

    System.out.flush();
}
catch (IOException e) { e.printStackTrace(); }

预先感谢

1 个答案:

答案 0 :(得分:1)

多亏了Abra,我才能够找到解决方案。对于以后查看此内容的任何人,下面的代码都适用:

// Create a new process and run the command
String[] command = new String[] {"mpw", "-u", "Name", "-t", "l", "Website"}; // Can also directly be put into the process builder as an argument without it being in an array
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();

OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();

// Store the input and output streams in a buffer
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
BufferedReader error = new BufferedReader(new InputStreamReader(stderr));

// Send input
writer.write("password\n"); // Don't forget the '\n' here, otherwise it'll continue to wait for input
writer.flush();
//writer.close(); // Add if doesn't work without it

// Display the output
String line;
while ((line = reader.readLine()) != null) System.out.println(line);
// Display any errors
while ((line = error.readLine()) != null) System.out.println(line);

这适用于任何命令,我从Writing to InputStream of a Java Process获得了解决方案