简体   繁体   中英

How do I read and write from an external process in Java?

I want to run PianoBar from a Java GUI (PianoBar is a program that runs Pandora from command line). I thought this would be quick and dirty, but I guess I don't know enough about interaction between programs.

I use ProcessBuilder to launch an instance of PianoBar like so:

    private Process createPianoBarProcess() throws IOException {
        String[] command = {"CMD", "/C", "pianobar"};
        ProcessBuilder probuilder = new ProcessBuilder( command );
        probuilder.redirectErrorStream(true);
        probuilder.directory(new File("~~location where pianobar.exe is~~"));
        Process process = probuilder.start();
        return process;
    }

After I create the process, I create a BufferedReader to read in the PianoBar output:

    Process pianoBar = createPianoBarProcess();

    InputStream inS = pianoBar.getInputStream();
    InputStreamReader isr = new InputStreamReader(inS);
    BufferedReader br = new BufferedReader(isr);

But when I read the output from PianoBar via this reader, it spits out the first line of PianoBar ("Welcome to pianobar (2013.05.19-win32)! Press ? for a list of commands."), then it spits out the next line ("[?] Email:"). Then it just hangs.

Obviously, it is waiting for the user to input their email. But no matter what I try, I can't get my Java program to write the email to the PianoBar process when prompted - it just hangs as soon as it reads out the last character.

Is it possible to do what I am trying to do? I thought it would be an easy thing to look for on the internet, but I haven't been able to find anything. All I want is an easy way to write to the external process when prompted. Seems like this should be easy...

You may use the following code snippet to get working:

String s;
//s = email
BufferedWriter bufferedwriter = new BufferedWriter(new OutputStreamWriter(pianoBar.getOutputStream()));
bufferedwriter.write(s);
bufferedwriter.flush();

Done! Remember to surround the code block with appropriate try/catch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM