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

ぃ、小莉子 提交于 2019-12-13 06:25:19

问题


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...


回答1:


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


来源:https://stackoverflow.com/questions/17483199/how-to-run-another-java-process-with-console-in-java-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!