简体   繁体   中英

Print original format of Java Process Inputstream

Just wondering if it is possible to keep the original format of the console messages redirected from an external Jar through java process inputstream.

I am invoking an external Jar tool and printing out its messages on the console. This is the code I use for it:

proc = rt.exec(java -jar External jar with arguments);
String line;
BufferedReader inMsg = new BufferedReader(
        new InputStreamReader(proc.getInputStream()));
while ((line = inMsg.readLine()) != null) {
    System.out.println(line);
}
in.close();

However, this external Jar program implements a progress bar to show file download process, which essentially updates the same line as:

private static void printProgBar(double bytesCopied) {
    double percentDone = ((bytesCopied)/(curretnFileSize));
    percentDone *= 100;
    StringBuilder bar = new StringBuilder("[");

    for (int i = 0; i < 50; i++) {
        if (i < (percentDone / 2)) {
            bar.append("=");
        } else if (i == (percentDone / 2)) {
            bar.append(">");
        } else {
            bar.append(" ");
        }
    }

    bar.append("]   ").append(df.format(percentDone)).append("%     ");
    if(percentDone > 1){
        System.out.print("\r" + bar.toString());
    }
}

Output is something like this:

[=======                                           ]   12.51%

Okay so when I redirect this through inputstream, it prints each change in the percentage on the new line. I want to respect the original format. Any suggestions, how can it be possible.

I think the problem is you are using println to write while the original output is written using print . \\r makes the cursor go to the beginning of the current line, but println make it one forward.

I'd try to use print instead of println . You could check if the line starts with a \\r character and if no, then add a new line after that.

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