实现控制台不换行输出进度条

package testPackage;

import com.hzb.base.util.BigDecimalUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.stream.Stream;

/**
 * @author hzb
 */
public class test {

    // 进度条最大长度
    private static final int total = 100;
    private static final char incomplete = '░';
    private static final char complete = '█';
    private static StringBuilder builder = new StringBuilder();

    public static void main(String[] args) throws IOException {


        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {

            Stream.generate(() -> incomplete).limit(total).forEach(builder::append);
            File file = new File("E:\\test\\resource\\子账号#5.xlsx");
            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream("E:\\test\\resource\\子账号#5_backUp.xlsx");

            System.out.println("下载的文件:" + file.getAbsolutePath());

            byte[] bytes = new byte[500000];
int len = 0;
            float process = 0f;
            boolean isDone = false;
            while((len = fileInputStream.read(bytes)) != -1) {

                Thread.sleep(1000);
                fileOutputStream.write(bytes, 0 , (int)len);
                process = new BigDecimal(process).add(
                        BigDecimalUtil.divide(new BigDecimal(len), new BigDecimal(file.length()), 2, BigDecimal.ROUND_HALF_DOWN)
                        .multiply(new BigDecimal(total))
                ).setScale(2, BigDecimal.ROUND_HALF_DOWN).floatValue();

                process = process > total ? total : process;
                if (total == process) {

                    isDone = true;
                }
                print(process);

            }

            if (!isDone) {

                print(total);
            }

            fileOutputStream.flush();

        } catch (FileNotFoundException e1) {

            e1.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        } finally {

            if (null != fileInputStream) {

                fileInputStream.close();
            }
            if (null != fileOutputStream) {

                fileOutputStream.close();
            }
        }
    }

    public static void print(float process) {

        int processInt = (int) process;

        for(int i =0; i< process; i++) {

           builder.replace(i, i+1, String.valueOf(complete));
           System.out.print("\r" + builder + " " + processInt + "%");
        }

        if (processInt == total) {

            System.out.println("下载完成!");
        }

    }
}

 

posted @ 2022-07-05 17:36  隐语者  阅读(195)  评论(0编辑  收藏  举报