Home > OS >  How to trigger console app on Linux from Java app
How to trigger console app on Linux from Java app

Time:11-24

I have console app in Ubuntu that receives as input just letter "a".

So when user types "a" in console - this triggers some other process.

Now I have Java app that would need to trigger this console app by passing "a" to it.

What would be best way to implement that? I just need few pointers.

Tried to find similar soulutons but no luck.

CodePudding user response:

Try this:

package stackoverflow;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ProcessAccess {



    public static void main(final String[] args) throws IOException {
        final Process process = Runtime.getRuntime().exec(args);

        // write text to os
        final OutputStream os = process.getOutputStream();
        os.write("a".getBytes());

        // maybe needs newline to simulate enter key, \n may be enough for windows
        // use any of the following 2
        final String lineSeparator1 = System.lineSeparator();
        final String lineSeparator2 = System.getProperty("line.separator");

        os.write(lineSeparator1.getBytes());

        os.flush(); // may not be needed, check out process.getOutputStream()'s documentation


        // quick and dirty reading of app output, you can do that a lot better
        final InputStream is = process.getInputStream();
        while (true) {
            final int b = is.read();
            if (b == -1) break;

            System.out.print((char) b);
        }

        // same quick dirty. remember you might need to use multi-threading or pseudo-parallel read if you depend on output of either in or err channel
        final InputStream es = process.getErrorStream();
        while (true) {
            final int b = es.read();
            if (b == -1) break;

            System.out.print((char) b);
        }
    }



}
  • Related