Search code examples
javaconsolecommandruntimeexecute

Java execute multiple console commands on loaded program


I want to load a program from the console and then execute commands on it later on. The loading works fine, but how can I execute commands on the loaded program without starting it every time I want to use it?

For example: ./randomapp command1 command2

But on Java, I have to usw ./randomapp command1 every time I want to execute something on it, so the program doesn't stay loaded.


Solution

  • Not knowing anything about your Java program or the app you'd like to execute and feed with commands, this is a shot in the dark. Also, all error handling is omitted. I'm using tee for the program to be run because it's convenient.

    public class Command {
        private static OutputStream os;
        private static OutputStreamWriter osw;
        private static Process process;
        public static void start(){
            try { 
                ProcessBuilder pb = new ProcessBuilder( "/usr/bin/tee", "x.dat" );
                process = pb.start();
                os = process.getOutputStream();
                osw = new OutputStreamWriter( os );
            } catch( Exception e ){
                // error handling
            } catch( Error e ){
                // error handling
            }
        }
    
        public static void terminate() throws Exception {
            process.waitFor();
        }
    
        public static void command( String str ) throws Exception {
            String cmd = str + System.lineSeparator();
            osw.write( cmd, 0, cmd.length() );
            osw.flush();
        }
    

    I've tested this using:

    Command.start();
    Command.command( "line 1" );
    Thread.sleep( 2000 );
    Command.command( "line 2" );
    Thread.sleep( 2000 );
    Command.command( "line 3" );
    Command.terminate();
    

    The lines can be found on x.dat.