سؤال

ولدي برنامج جافا تعمل في وضع سطر الأوامر. أود أن عرض شريط التقدم وتظهر النسبة المئوية من المهمة. نفس النوع من شريط التقدم سوف تشاهد باستخدام مجلد مشترك تحت يونيكس. هل هذا ممكن؟

هل كانت مفيدة؟

المحلول

ولقد نفذت هذا الشيء من قبل. ليست الكثير عن جافا، ولكن ما الأحرف لإرسالها إلى وحدة التحكم.

والمفتاح هو الفرق بين \n و\r. \n يذهب إلى بداية سطر جديد. ولكن هل \r فقط <م> إرجاع - انه يعود الى بداية السطر نفسه

وهكذا ما ينبغي القيام به هو طباعة شريط التقدم، على سبيل المثال، عن طريق طباعة سلسلة

"|========        |\r"

في القراد القادمة من شريط التقدم، الكتابة فوق نفس الخط مع شريط أطول. (لأننا تستخدم \ ص، نبقى على نفس الخط) على سبيل المثال:

"|=========       |\r"

وماذا عليك أن تتذكر القيام به، هو عندما تنتهي من ذلك، إذا كنت ثم طباعة فقط

"done!\n"

وأنت قد لا تزال لديها بعض القمامة من شريط تقدم على خط المرمى. حتى بعد الانتهاء مع شريط التقدم، تأكد من طباعة ما يكفي بيضاء لإزالته من على خط المرمى. مثل:

"done             |\n"

وعلى أمل أن يساعد.

نصائح أخرى

وهناك https://github.com/ctongfei/progressbar أو الترخيص: MIT

وبسيط شريط التقدم وحدة التحكم. شريط التقدم الكتابة يعمل الآن على موضوع آخر.

ينصح

ومينلو، فيرا مونو، رمز مصدر Pro أو SF مونو للتأثيرات البصرية المثلى.

لConsolas أو أندل مونو الخطوط، استخدم ProgressBarStyle.ASCII (انظر أدناه) لأنه لم يتم محاذاة رموزا رسم مربع بشكل صحيح في هذه الخطوط.

ومخضرم:

<dependency>
  <groupId>me.tongfei</groupId>
  <artifactId>progressbar</artifactId>
  <version>0.5.5</version>
</dependency>

والاستعمال:

ProgressBar pb = new ProgressBar("Test", 100); // name, initial max
 // Use ProgressBar("Test", 100, ProgressBarStyle.ASCII) if you want ASCII output style
pb.start(); // the progress bar starts timing
// Or you could combine these two lines like this:
//   ProgressBar pb = new ProgressBar("Test", 100).start();
some loop {
  ...
  pb.step(); // step by 1
  pb.stepBy(n); // step by n
  ...
  pb.stepTo(n); // step directly to n
  ...
  pb.maxHint(n);
  // reset the max of this progress bar as n. This may be useful when the program
  // gets new information about the current progress.
  // Can set n to be less than zero: this means that this progress bar would become
  // indefinite: the max would be unknown.
  ...
  pb.setExtraMessage("Reading..."); // Set extra message to display at the end of the bar
}
pb.stop() // stops the progress bar

ولقد وجدت البرمجية التالية للعمل بشكل صحيح. فإنه يكتب بايت إلى المخزن المؤقت للإخراج. ربما أن أساليب استخدام الكاتب مثل طريقة System.out.println() محل تواجد \r إلى \n لتتناسب مع خط الأصلي المستهدف إنهاء (إذا لم يتم تكوين بشكل صحيح).

public class Main{
    public static void main(String[] arg) throws Exception {
        String anim= "|/-\\";
        for (int x =0 ; x < 100 ; x++) {
            String data = "\r" + anim.charAt(x % anim.length()) + " " + x;
            System.out.write(data.getBytes());
            Thread.sleep(100);
        }
    }
}

ولقد جعلت من التقدم نسبة عارية للتحقق من يبقى ملف التحميل.

وأنا استدعاء الأسلوب بشكل دوري في بلدي ملف التحميل للتحقق من إجمالي ملف الحجم والمتبقية وتقديم أنه في %.

ويمكن استخدامه لهذا الغرض مهمة أخرى كذلك.

واختبار والمثال الناتج

progressPercentage(0, 1000);
[----------] 0%

progressPercentage(10, 100);
[*---------] 10%

progressPercentage(500000, 1000000);
[*****-----] 50%

progressPercentage(90, 100);
[*********-] 90%

progressPercentage(1000, 1000);
[**********] 100%

واختبار مع لحلقة

for (int i = 0; i <= 200; i = i + 20) {
    progressPercentage(i, 200);
    try {
        Thread.sleep(500);
    } catch (Exception e) {
    }
}

وهذه الطريقة يمكن تعديلها بسهولة:

public static void progressPercentage(int remain, int total) {
    if (remain > total) {
        throw new IllegalArgumentException();
    }
    int maxBareSize = 10; // 10unit for 100%
    int remainProcent = ((100 * remain) / total) / maxBareSize;
    char defaultChar = '-';
    String icon = "*";
    String bare = new String(new char[maxBareSize]).replace('\0', defaultChar) + "]";
    StringBuilder bareDone = new StringBuilder();
    bareDone.append("[");
    for (int i = 0; i < remainProcent; i++) {
        bareDone.append(icon);
    }
    String bareRemain = bare.substring(remainProcent, bare.length());
    System.out.print("\r" + bareDone + bareRemain + " " + remainProcent * 10 + "%");
    if (remain == total) {
        System.out.print("\n");
    }
}

وC # مثال لكنني أفترض هذا هو نفسه بالنسبة لSystem.out.print في جاوة. لا تتردد في تصحيح لي إذا كنت مخطئا.

وأساسا، وتريد لكتابة الحرف \r الهروب إلى بداية رسالتك والذي يؤدي المؤشر للعودة إلى بداية السطر (خط تغذية) من دون الانتقال إلى السطر التالي.

    static string DisplayBar(int i)
    {
        StringBuilder sb = new StringBuilder();

        int x = i / 2;
        sb.Append("|");
        for (int k = 0; k < 50; k++)
            sb.AppendFormat("{0}", ((x <= k) ? " " : "="));
        sb.Append("|");

        return sb.ToString();
    }

    static void Main(string[] args)
    {
        for (int i = 0; i <= 100; i++)
        {
            System.Threading.Thread.Sleep(200);
            Console.Write("\r{0} {1}% Done", DisplayBar(i), i);
        }

        Console.ReadLine();

    }

وهنا هو نسخة معدلة من أعلاه:

private static boolean loading = true;
private static synchronized void loading(String msg) throws IOException, InterruptedException {
    System.out.println(msg);
    Thread th = new Thread() {
        @Override
        public void run() {
            try {
                System.out.write("\r|".getBytes());
                while(loading) {
                    System.out.write("-".getBytes());
                    Thread.sleep(500);
                }
                System.out.write("| Done \r\n".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    th.start();
}

... وفي رئيسية هي:

loading("Calculating ...");

وهذا من شأنه أن يكون من الممكن مع مكتبة جافا اللعنات. هذا عبارة ما وجدت. أنا لم تستخدم ذلك بنفسي وأنا لا أعرف ما إذا كان هو عبر منصة.

ويمكنني استخدام "كذاب" شريط التقدم عندما كنت في حاجة لتأخير أداة لمنع حالة تعارض.

private void delay(long milliseconds) {
    String bar = "[--------------------]";
    String icon = "%";

    long startTime = new Date().getTime();
    boolean bouncePositive = true;
    int barPosition = 0;

    while((new Date().getTime() - startTime) < milliseconds) {
        if(barPosition < bar.length() && barPosition > 0) {
            String b1 = bar.substring(0, barPosition);
            String b2 = bar.substring(barPosition);
            System.out.print("\r Delaying: " + b1 + icon + b2);
            if(bouncePositive) barPosition++;
            else barPosition--;
        } if(barPosition == bar.length()) {
            barPosition--;
            bouncePositive = false;
        } if(barPosition == 0) {
            barPosition++;
            bouncePositive = true;
        }

        try { Thread.sleep(100); }
        catch (Exception e) {}
    }
    System.out.print("\n");
}

ولقد واجهت في الآونة الأخيرة من نفس المشكلة، يمكنك التحقق قانون بلدي: لقد تعيينها ل# واحد على 5٪، والتي يمكنك تعديل في وقت لاحق.

public static void main (String[] args) throws java.lang.Exception
{
    int i = 0;
    while(i < 21) {
        System.out.print("[");
        for (int j=0;j<i;j++) {
            System.out.print("#");
        }

        for (int j=0;j<20-i;j++) {
            System.out.print(" ");
        }

        System.out.print("] "+  i*5 + "%");
        if(i<20) {
            System.out.print("\r");
            Thread.sleep(300);
        }
        i++;
    }
    System.out.println();
}
public static void main(String[] argv) throws Exception{


    System.out.write("\r".getBytes());
    int percentage =10;
    while(percentage <= 100) {
        String temp =generateStars(percentage);
        System.out.write(temp.getBytes());
        System.out.print("\b\b\b");
        percentage = percentage+10;
        Thread.sleep(500);
    }
}

    public static String generateStars(int percentage)
    {
        int startsNum = percentage / 4;
        StringBuilder builder = new StringBuilder();
        while(startsNum >= 0)
        {
        builder.append("*");
        startsNum--;
        }
        builder.append(percentage+"%");
        return builder.toString();
    }

وقليلا ريفاكتوريد وتحديثها @ طريقة ميثم-ɯɐɥʇʎɐɯ الصورة. الآن انها تدعم حجم التعسفي من شريط التقدم:

    public static void progressPercentage(int done, int total) {
        int size = 5;
        String iconLeftBoundary = "[";
        String iconDone = "=";
        String iconRemain = ".";
        String iconRightBoundary = "]";

        if (done > total) {
            throw new IllegalArgumentException();
        }
        int donePercents = (100 * done) / total;
        int doneLength = size * donePercents / 100;

        StringBuilder bar = new StringBuilder(iconLeftBoundary);
        for (int i = 0; i < size; i++) {
            if (i < doneLength) {
                bar.append(iconDone);
            } else {
                bar.append(iconRemain);
            }
        }
        bar.append(iconRightBoundary);

        System.out.print("\r" + bar + " " + donePercents + "%");

        if (done == total) {
            System.out.print("\n");
        }
    }
public class ProgressBar
{
    private int max;

    public ProgressBar(int max0) {
        max = max0;
        update(0);
    }

    public void update(int perc) {
        String toPrint = "|";
        for(int i = 0; i < max; i++) {
            if(i <= (perc + 1))
                toPrint += "=";
            else
                toPrint += " ";
        }

        if(perc >= max)
            Console.print("\r");
        else
            Console.print(toPrint + "|\r");
    }
}
public class Main {

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

        System.out.println("Loading : ");
            int count =1;
            for(int j=1;j<150;j++){

                System.out.print("\r");
                if(count==1){
                    System.out.print("/");
                    count++;
                }
                else if(count==2){
                    System.out.print("|");
                    count++;
                }
                else if(count==3){
                    System.out.print("-");
                    count++;
                }
                else if(count==4){
                    System.out.print("\\");
                    count++;
                }
                else if(count==5){
                    System.out.print("|");
                    count++;
                }
                else
                    count = 1;
            Thread.sleep(200);
        }

        }

    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top