using xterm with java

2019-08-13 14:17发布

问题:

first of all, I found a lot of questions about xterm and java, but no questions handles my problem directly.

What is my problem? I want to start a xterm terminal from java and I want to send commands to this terminal. First I just want to change the directory, but it does not work. But it is important, that I don't know all commands at the beginning of the program, so it is recommended, that I can send commands to the terminal at run-time.

Here is my code:

String[] command= {"xterm"}; 
    Runtime rt = Runtime.getRuntime();  
    Process pr = rt.exec(command);

    Thread.sleep(2000);

    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    ReadThread input = new ReadThread(in);
    input.start();

    BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    ReadThread inputError = new ReadThread(error);
    inputError.start();

    PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(pr.getOutputStream())),true);
    printWriter.println("cd /home/***/sipp/sipp-3.3\n");
    Thread.sleep(2000);

    input.die();
    inputError.die();
    printWriter.close();
    error.close();
    in.close();
    pr.destroy();

I thought that the terminal will open (it does) and change the directory to sipp-3.3 after 2 seconds. Another 2 seconds later the xterm should close (it does). But what is the problem, that my command does not work? And please I don't want to find a solution like

String [] gggg = {"xterm", "-c", "multiple commands, with |, &&, ; etc"};
rt.exec(gggg);

Because with a solution like this, I am not able to send further commands to the terminal. Many thanks in advance!

标签: java linux xterm