Search code examples
javalinuxprocessxtermx11

How to run another java process with console in java (in Linux)


How can I run an another java process (with a console) in Linux?

I know I should use ProcessBuilder or Runtime.getRuntime().exec() to execute a command, but I want to know how I can show an separate X-window command terminal (ex. /usr/bin/xterm) or at least show an console-terminal looking window and run a java process with stdin,stdout,stderr on that.

Is there any solution? I heard the Process.getOutputStream() doesn't work on xterm, but haven't tried it yet (Because I'm using Windows..)

EDIT: The java program I want to execute uses jline, which uses JNI...


Solution

  • To start terminl you can simply run following code:

    new ProcessBuilder("/usr/bin/xterm").start();
    

    But I guess, that is not you really need. Because, even you pass command to run, let's say ls as argument:

    new ProcessBuilder("/usr/bin/xterm", "-e", "ls").start();
    

    You will get output from xterm(not from ls). If you want to start process and get output, you need to do it like that:

    public static void main(String[] args) throws Exception {
        // get content of the "/usr/bin" directory
        ProcessBuilder pb = new ProcessBuilder("ls", "/usr/bin");
        pb.redirectErrorStream(true);
    
        Process p = pb.start();
        InputStream is = p.getInputStream();
        System.out.println(toString(is));
        is.close();
    }
    
    public static String toString(InputStream is) throws IOException {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
        return writer.toString();
    }