简体   繁体   中英

How to execute multiple commands interactively in linux terminal from Java?

I want to run multiple commands in the linux terminal and that will be one like as follows:

1. I will run suppose torch and i wrote th command and it opened the torch promt.
2. Now if i execute next command from java then it will run in the torch promt of the linux terminal.

you can take another example like:

1. At fist i will run python in the linux terminal from java.
2. Then run 1+1 or anything in the python interpreter from java.
So here my second command is dependent on the first command. I want to run the commands in the terminal in a sequential way.

Edit : Another approach will do.Suppose i have a python interpreter running in linux terminal and now i want to execute a command from java that will run in the python interpreter of that particular opened linux terminal. Can i do that??

I have tried to to run a command using this:

        String line;
            try
            {

                String execstr= "th"; //It opens the torch promt in linux terminal.

                Process p = Runtime.getRuntime().exec(execstr);
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

                /*if((line= input.readLine())==null)
                    System.out.println("blank");*/

                while ((line = input.readLine()) != null) 
                {
                    System.out.println(line);
                }
                input.close();
            }
            catch(Exception e)
            {

                e.printStackTrace();
            }

        }
    }

But now after this command how can i run a command from java in the promt that means i want it interactively ??

So how can i save the state of the previous command and use it for the next command??

Use p.getOutputStream() to get a stream into which you can write the desired input for the program you run. (I know, the naming is a bit confusing).

Just the relevant part:

    Process p = Runtime.getRuntime().exec(execstr);
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    OutputStream ops = p.getOutputStream();
    ops.write("echo hello world".getBytes());
    ops.close();            

    while ((line = input.readLine()) != null) 
    {
       System.out.println(line);
    }
    input.close();

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