简体   繁体   中英

Java getting output from program executed in command line when it constantly updates a single line in the command prompt

I have a quick question about getting output from specific instances of programs my java program runs through the command line. I am able to get the output for programs as long as they output multiple lines, but if it is a program that updates the current line I seem to be out of luck. For example when I try to convert an mp4 to an mp3 using ffmpeg it will only have a single line with the files current size and time taken to run which I can't seem to get when running it through my java program. Here is the code I use which works when there are multiple lines:

InputStream is = pr.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    System.out.printf("Output of running %s is:\n",
            Arrays.toString(command1));
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    try {
        int exitValue = pr.waitFor();
        System.out.println("\n\nExit Value is " + exitValue);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

Any help would be much appreciated! Thanks!

I think I see what's going on. readLine() is looking for a '\\n' character. Single-line programs emit a '\\r' to return to the beginning of the line and re-write it over and over.

I read around commons-io and javadocs and neither of them have a readLine(char c) which would read until a particular character is encountered, so unfortunately I think you have to code this up for yourself. :\\

If you use br.readLine() you need to be certain that it is terminated.

From javadoc https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed.

Using read() only and printing the characters one by one might be easier

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