Trinculo
Trinculo

Reputation: 2021

Sending user input to console in Java

I am trying to write something in Java to automatically import a certificate. When entering this command in the command shell:

    keytool -import -keystore c:\.truststore -alias xenv -file cacert.pem

it asks me for 2 questions: the password and if I want to confirm. In Python, I can use subprocess.Popen as follows:

p = subprocess.Popen("keytool","-import","-keystore","c:\\.truststore","-alias","xenv","-file","cacert.pem", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate("password\n" + "y\n")

I am now attempting to do something similar in Java. I think I'm on the right track after a few hours of playing around, but I can't quite get it to work. Any idea what I am doing wrong? Thanks in advance!

import java.io.*;

public class PropertyTest {

    public static void main(String[] args) throws IOException {
        ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "keytool", "-import", "-keystore", "c:\\.truststore", "-alias", "xenv", "-file", "c:\\cacert.pem");
        pb.redirectErrorStream(true);
        Process p = pb.start();
        OutputStream out = p.getOutputStream();
        out.write("password\n".getBytes());
        out.write("y\n".getBytes());
    }
}

Upvotes: 0

Views: 1989

Answers (1)

Trinculo
Trinculo

Reputation: 2021

This worked. I changed it to a BufferedWriter and flushed and closed it when I was done. Hopefully this helps someone else out who is stuck on a similar problem!

    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "keytool", "-import", "-keystore", "c:\\.truststore", "-alias", "alias", "-file", "c:\\cacert.pem");
    pb.redirectErrorStream(true);
    Process p = pb.start();
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    out.write("allgoodthings\n");
    out.write("y\n");
    out.flush();
    out.close();

Upvotes: 1

Related Questions