How to send a string to the terminal without having it to be a standard command?

牧云@^-^@ 提交于 2019-12-02 00:03:58

Your immediate problem is that you are starting separate processes for each of the 'commands' you are invoking. The password 'command' is being issued to a process that is totally unaware of the previous 'login' command.

Having said that, your more dire problem is a serious misunderstanding of what the Process class is used for and how to interact with external programs from within Java.

Here's one tutorial that may help further your education on the topic, I would advise Googling for others.

I have found the answer to my question.

The problem was that the second response of the terminal was in fact in the first one, and the password had to be sent in the middle of it. Here is the code (I agree, my explanation is a little vague) :

    String s="";
    Process p = Runtime.getRuntime().exec("p4 login");     
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));    
    char a=(char)in.read();
    while(a>0 && a<256)
    {

        a=(char)in.read();
        if(nb==14) new PrintWriter(p.getOutputStream(),true).println(password); 
        if(nb>16) s=s+a;
        nb++;
    }
    if(s.startsWith("User")) loggedIn=true;
    else loggedIn=false;

In order to communicate with a process, you don't start another process but write to its stdin. There's actually code in there that tries to do such a thing. Have sendLoginCommand return the created process; delete all code in sendPassword, in fact delete the whole method. In your main code write your password to the process's output stream. So what I'm saying is

new PrintWriter(sendLoginCommand().getOutputStream()).println(password);

As a side note, i strongly advice to use a pre-packaged library that already encapsulates all the technical stuff about the process communication in Java.

A good library about that is commons-exec (http://commons.apache.org/exec/.

It comes with command line helper, background thread to read the sysout/syserr output, an optional watchdog to kill the process after a given amount of time, and so on (it works of course on nearly all os).

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