简体   繁体   中英

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). The commands will be given by the user like changing directory, compiling a C program etc. The command list is not fixed.

I have also tried and use the /bin/bash -c method and the following as well.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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