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

后端 未结 4 529
不知归路
不知归路 2020-12-12 00:57

My part of java code is below.

while (status == DOWNLOADING) {
    /* Size buffer according to how much of the
       file is left to download. */
                   


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 01:24

    This is a simple "progress bar" concept.

    Basically it uses the \b character to backspace over characters previously printed to the console before printing out the new progress bar...

    public class TextProgress {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            System.out.println("");
            printProgress(0);
            try {
                for (int index = 0; index < 101; index++) {
                    printProgress(index);
                    Thread.sleep(125);
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(TextProgress.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
        public static void printProgress(int index) {
    
            int dotCount = (int) (index / 10f);
            StringBuilder sb = new StringBuilder("[");
            for (int count = 0; count < dotCount; count++) {
                sb.append(".");
            }
            for (int count = dotCount; count < 10; count++) {
                sb.append(" ");
            }
            sb.append("]");
            for (int count = 0; count < sb.length(); count++) {
                System.out.print("\b");
            }
            System.out.print(sb.toString());
    
        }
    }
    

    It won't work from within most IDE's, as Java's text components don't support the \b character, you must run from the terminal/console

提交回复
热议问题