Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

download - How to show percentage progress of a downloading file in java console(without UI)?

My part of java code is below.

while (status == DOWNLOADING) {
    /* Size buffer according to how much of the
       file is left to download. */
            byte buffer[];
            if (size - downloaded > MAX_BUFFER_SIZE) {
                buffer = new byte[MAX_BUFFER_SIZE];
            } else {
                buffer = new byte[size - downloaded];
            }

            // Read from server into buffer.
            int read = stream.read(buffer);
            if (read == -1){
                System.out.println("File was downloaded");
                break;
            }

            // Write buffer to file.
            file.write(buffer, 0, read);
            downloaded += read;

        }

  /* Change status to complete if this point was
     reached because downloading has finished. */
        if (status == DOWNLOADING) {
            status = COMPLETE;

        }

I want to show the progress of the downloading file as percentage by updating the progress line in console. Please help. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are satisfied with output like

Downloading file ... 10% ... 20% ... 38% ...

that keeps appending to the line, you can just print instead of println. If you want to do something limited like just update a few characters in place, you can print the backspace character to erase then re-print the percent, for example:

System.out.print("index at: X");
int lastSize = 1;
for (int i = 0; i < 100; i++) {
  for (int j = 0; j < lastSize; j++) {
    System.out.print("");
  }
  String is = String.toString(i);
  System.out.print(is);
  lastSize = is.length();
}

Note how the code tracks how many characters were printed, so it knows how many backspaces to print to erase the appended text.

Something more complex than that, you need some sort of console or terminal control SDK. ncurses is the Unix standard, and it looks like there's a Java port:

http://sourceforge.net/projects/javacurses/

I have never used this one so I can't vouch for it. If it's not right, a quick Google showed many alternatives.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...