java - Reading other process' **unbuffered** output stream -
java - Reading other process' **unbuffered** output stream -
i'm programming little gui file converter in java. file converter writes current progress stdout. looks this:
flow_1.wav: 28% complete, ratio=0,447
i wanted illustrate in progress bar, i'm reading process' stdout this:
processbuilder builder = new processbuilder("..."); builder.redirecterrorstream(true); process proc = builder.start(); inputstream stream = proc.getinputstream(); byte[] b = new byte[32]; int length; while (true) { length = stream.read(b); if (length < 0) break; // processing info } now problem regardless byte array size choose, stream read in chunks of 4 kb. code beingness executed until length = stream.read(b); , blocks quite while. 1 time process generates 4 kb output data, programm gets chunk , works through in 32 byte slices. , waits 1 time again next 4 kb.
i tried forcefulness java utilize smaller buffers this:
bufferedinputstream stream = new bufferedinputstream(proc.getinputstream(), 32); or this:
bufferedreader reader = new bufferedreader(new inputstreamreader(proc.getinputstream()), 32); but neither changed anything.
then found this: process source (around line 87)
it seems process class implemented in such way pipes process' stdout file. proc.getinputstream(); does, returning stream file. , file seems written 4 kb buffer.
does know kind of workaround situation? want process' output instantly.
edit: suggested ian roberts, tried pipe converter's output stderr stream, since stream doesn't seem wrapped in bufferedinputstream. still 4k chunks.
another interesting thing is: don't 4096 bytes, 5 more. i'm afraid fileinputstream buffered natively.
looking @ code linked process's standard output stream gets wrapped in bufferedinputstream standard error remains unbuffered. 1 possibility might execute not converter directly, shell script (or windows equivalent if you're on windows) sends converter's stdout stderr:
processbuilder builder = new processbuilder("/bin/sh", "-c", "exec /path/to/converter args 1>&2"); don't redirecterrorstream, , read proc.geterrorstream() instead of proc.getinputstream().
it may case converter using stderr progress reporting in case don't need script bit, turn off redirecterrorstream(). if converter programme writes both stdout , stderr you'll need spawn sec thread consume stdout (the script approach gets around sending stderr).
java process stream stdout unbuffered
Comments
Post a Comment