How to send a string to the terminal without a standard command?

I am writing a Java program that should use a terminal command to work. My function basically looks like this:

public void sendLoginCommand() throws IOException
{
    System.out.println("\n------------Sending Login Command------------\n");
    String cmd="qskdjqhsdqsd";
    Runtime rt = Runtime.getRuntime();
    Process p=rt.exec(cmd);
}
public Process sendPassword(String password) throws IOException
{
    System.out.println("\n------------Sending Password------------\n");
    String cmd=password;
    Runtime rt = Runtime.getRuntime();
    Process p=rt.exec(cmd);
    return p;
}
public void login(String password) throws IOException
{
    sendLoginCommand();
    Process p = sendPassword(password);
    System.out.println("\n------------Reading Terminal Output------------\n");
    Reader in = new InputStreamReader(p.getInputStream());

    in = new BufferedReader(in);
    char[] buffer = new char[20];
    int len = in.read(buffer);
    String s = new String(buffer, 0, len);
    System.out.println(s);
    if(s.equals("Password invalid.")) loggedIn=false;
    else loggedIn=true;
}

Here, the program correctly sends the p4 login command, but then the terminal asks for the password. When I use the same lines as with sendLoginCommand (), the program returns an error. Apparently, we can only send standard throught Process commands. I was hoping someone knew how to send a normal string to the terminal

Thank you in advance

+3
source share
4 answers

I found the answer to my question.

, , . ( , ):

    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;
+1

, , . "" , "login".

, - , Process Java.

tutorial, , Googling .

+3

, , stdin. , . sendLoginCommand ; sendPassword, . .

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

, Java.

commons-exec (http://commons.apache.org/exec/.

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

0
source

All Articles