java - Sending output to external process -
for reason, i'm having problems sending output process i've created in java. external process running in command prompt, , peculiar thing can click that, type, hit enter, , i'll output program. addition program can read output coming program, can't send it.
anyways, here relevant code i'm using isn't working...
try { processbuilder builder=new processbuilder(args); builder.redirecterrorstream(true); final process p=builder.start(); // process has been created , running try { string b=""; bufferedreader input = new bufferedreader(new inputstreamreader(p.getinputstream())); final bufferedwriter output = new bufferedwriter(new outputstreamwriter(p.getoutputstream())); new thread(){public void run(){ // thread periodically send "get_time" process update on progress while(true) { try { thread.sleep(1000); p.exitvalue(); // p.exitvalue() works when process has ended, normal code goes in catch block output.close(); break; // leave infinite loop if program has closed } catch (ioexception ex) { logger.getlogger(ovmusicui.class.getname()).log(level.severe, null, ex); break; // leave infinite loop if tried closing our output stream, closed } catch (interruptedexception ex) { logger.getlogger(ovmusicui.class.getname()).log(level.severe, null, ex); } catch (illegalthreadstateexception e) { try { system.out.println("outputted: get_time"); output.write("get_time" + system.lineseparator()); output.flush(); // give process input } catch (ioexception ex) { logger.getlogger(ovmusicui.class.getname()).log(level.severe, null, ex); } } } }}.start(); while((b = input.readline()) != null){ system.out.println(new time(system.currenttimemillis()).tostring() + " " + b); // log output process gives } input.close(); } catch (ioexception ex) { logger.getlogger(ovmusicui.class.getname()).log(level.severe, null, ex); } // more code here } catch (ioexception ex) { logger.getlogger(ovmusicui.class.getname()).log(level.severe, null, ex); }
if necessary, can give example command , name of external program being run can try yourself...
thanks!
edit: here example of what's passed processbuilder: arrays.aslist("vlc\vlc.exe", "-irc", "-vvv", "http://www.youtube.com/watch?v=xfeys7jfnx8", "--sout", "file/ogg:untitled 1.ogg", "--play-and-exit", "--rc-quiet")
. difference use absolute paths instead of relative paths. program vlc media player 2.0.7.
your code has few problems. first, should not use exceptions regular control flow: it's expensive, it's difficult read, , makes handling actual errors more difficult. it's better spawn thread
calls p.waitfor()
, signals main thread complete, such wait
/notify
.
also, construction infinite loop , using break
instead of return
make code more difficult debug; instead, use timer
.
it looks output external program working correctly problem reading output. program may buffering own output or may detecting it's not being run interactively , behaving differently.
Comments
Post a Comment