1. 程式人生 > 實用技巧 >使用java實現在下載檔案的過程中顯示進度條,簡單例子

使用java實現在下載檔案的過程中顯示進度條,簡單例子

package com.file;

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;


// 使用java實現在下載檔案的過程中顯示進度條
public class TestFile {

    public static class ProgressBarThread implements Runnable {
        private ArrayList<Integer> proList = new ArrayList<Integer>();
        private int progress; //當前進度
        private int totalSize; //總大小
        private boolean run = true;

        public ProgressBarThread(int totalSize) {
            this.totalSize = totalSize;
            //TODO 建立進度條
        }

        /**
         * @param progress 進度
         */
        public void updateProgress(int progress) {
            synchronized (this.proList) {
                if (this.run) {
                    this.proList.add( progress );
                    this.proList.notify();
                }
            }
        }

        public void finish() {
            this.run = false;
            //關閉進度條
        }

        @Override
        public void run() {
            synchronized (this.proList) {
                try {
                    while (this.run) {
                        if (this.proList.size() == 0) {
                            this.proList.wait();
                        }
                        synchronized (proList) {
                            this.progress += this.proList.remove( 0 );
                            //TODO 更新進度條
                            DecimalFormat decimalFormat = new DecimalFormat( "0.00" );
                            System.err.println( "當前進度:" + decimalFormat.format( this.progress / (float) this.totalSize * 100 ) + "%" );
                        }
                    }

                    System.out.println( "下載完成" );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  

測試程式碼

    // 測試
    public static void main(String[] args) {
        try {
            File file = new File( "/Users/zhenning/Documents/tools/mysql51.docset.zip" );
            FileInputStream fis = new FileInputStream( file );
            FileOutputStream fos = new FileOutputStream( "/Users/zhenning/Desktop/mysql51.docset.zip" );
            ProgressBarThread pbt = new ProgressBarThread( (int) file.length() );//建立進度條
            new Thread( pbt ).start();//開啟執行緒,重新整理進度條
            byte[] buf = new byte[1024];
            int size = 0;
            while ((size = fis.read( buf )) > -1) { //迴圈讀取
                fos.write( buf, 0, size );
                pbt.updateProgress( size );//寫完一次,更新進度條
            }
            pbt.finish(); //檔案讀取完成,關閉進度條
            fos.flush();
            fos.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }