简体   繁体   English

打开外壳并使用Java进行交互

[英]opening a shell and interact with using Java

I had previously asked the same question but with no answer, and have found some other questions similar to this problem here and here but again with no appropriate answers. 我以前曾问过同样的问题,但没有答案, 在这里这里 ,也发现了一些与此问题类似的其他问题,但又没有合适的答案。 Can anyone please help me out with this. 谁能帮我这个忙。 I am trying to open a shell from Java and interact with it (write commands and read the shell's output). 我正在尝试从Java打开外壳程序并与之交互(编写命令并读取外壳程序的输出)。 The commands will be given by the user like changing directory, compiling a C program etc. The command list is not fixed. 这些命令将由用户给出,例如更改目录,编译C程序等。命令列表不是固定的。

I have also tried and use the /bin/bash -c method and the following as well. 我也尝试过使用/ bin / bash -c方法以及以下方法。

Process p = new ProcessBuilder("xterm").start();

Process p = new ProcessBuilder("/bin/bash").start();

Thanks and I hope that the problem is clear. 谢谢,我希望问题已经解决。

Example of workable solution will be almost like below 可行解决方案的示例几乎如下所示

   Process process;

   rt = Runtime.getRuntime();

try 
{

    process = rt.exec(new String[]{"bash","-c","ls -al /home/"});

    log.warn("message to display");

    BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));

    String line=null;

    while((line=input.readLine()) != null) {

        log.warn(line);
    }

    int exitVal = process.waitFor();

    log.warn("Exited with error code : "+ exitVal);

}
catch (IOException e) 
{
    log.warn("IO Execption 1 Happen : " + e.getMessage());
} 
catch (Exception e) 
{
    log.warn("Execption Happen : " + e.getMessage());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM