progressbar

repository·main·Indexed 22 days ago

https://github.com/ctongfei/progressbar

A lightweight console progress bar library for the JVM designed with minimal runtime overhead. It supports declarative usage by wrapping collections, streams, and I/O operations (InputStream, Reader, etc.), as well as imperative control via a try-with-resources pattern. Features include a ProgressBarBuilder for customizing visual styles, units, and ETA functions, support for multiple concurrent bars, and integration with loggers like SLF4J via DelegatingProgressBarConsumer.

Tokens
3.8K
Snippets
14
Records
15
Agent score
78%

What's inside progressbar

  1. Use Kotlin DSL-like builders via progressbar-ktx

    main

    For Kotlin users, Kotlin DSL-like builders are available through the reimersoftware/progressbar-ktx repository. This extension provides a more idiomatic Kotlin experience for interacting with the progressbar library.

    https://github.com/reimersoftware/progressbar-ktx
  2. Customize a progress bar style with a builder

    main

    Since version 0.10.0, you can create a fully custom progress bar style using ProgressBarStyle.builder(). This allows you to define specific ANSI color codes and the characters used for the bar's structure.

    Available customization options include:

    • colorCode(byte): The ANSI color code.
    • leftBracket(String): The character used for the left side of the bar.
    • rightBracket(String): The character used for the right side of the bar.
    • block(char): The character used to represent the filled portion of the bar.
    • rightSideFractionSymbol(char): The character used for the remaining/fractional portion of the bar.
    ProgressBarBuilder pbb = ProgressBar.builder()
        // ...
        .setStyle(ProgressBarStyle.builder()
                          .colorCode((byte) 33)  // the ANSI color code
                          .leftBracket("{")
                          .rightBracket("}")
                          .block('-')
                          .rightSideFractionSymbol('+')
                          .build()
       ) // ...
  3. Use the try-with-resources pattern for ProgressBar

    main

    Since version 0.7.0, you must use the Java try-with-resources pattern when creating a ProgressBar. This ensures that the progress bar threads are terminated safely once the work is complete. The progress bar will automatically stop when the try block is exited.

    try (ProgressBar pb = new ProgressBar("Test", 100)) {
        // Your work here
    }
  4. Install progressbar via Maven

    main

    Add the following dependency to your pom.xml to use the progressbar library in your JVM project. Replace $VERSION with the desired version (e.g., 0.10.2).

      <dependency>
          <groupId>me.tongfei</groupId>
          <artifactId>progressbar</artifactId>
          <version>$VERSION</version>
      </dependency>
  5. Integrate progressbar with loggers like SLF4J

    main

    To redirect progress bar output to a logging framework (such as slf4j) instead of standard output, you must use the DelegatingProgressBarConsumer. This consumer accepts a lambda expression representing the logger method you wish to use (e.g., logger::info, logger::debug).

    This approach allows progress updates to be captured by your application's existing logging infrastructure, which is useful for file logging, log rotation, or centralized logging systems.

    // create logger using slf4j
    final Logger logger = LoggerFactory.getLogger("Test");
    
    try (ProgressBar pb = new ProgressBarBuilder()
            .setInitialMax(100)
            .setTaskName("Test")
            .setConsumer(new DelegatingProgressBarConsumer(logger::info))
            .build()) {
        // your task logic here
    }
  6. Use declarative usage with ProgressBar.wrap()

    main

    Since version 0.6.0, the preferred way to use a progress bar is via declarative usage. You can wrap a stream or collection with ProgressBar.wrap(...) so that the progress bar automatically tracks progress during iteration, reading, or writing. The wrapped object retains its original type.

    Supported types include:

    • Arrays (T[])
    • java.lang.Iterable<T>
    • java.util.Iterator<T>
    • java.io.InputStream (tracks bytes)
    • java.io.Reader (tracks characters)
    • java.io.OutputStream (dual of InputStream)
    • java.io.Writer (dual of Reader)
    • java.util.Spliterator<T>
    • java.util.Stream<T> (any S extending BaseStream<T, S>. Note: wrapping primitive streams may incur boxing overhead).
    // Basic syntax for wrapping a collection with a task name
    ProgressBar.wrap(collection, "Task Name")
    
    // Using a ProgressBarBuilder for customization
    ProgressBarBuilder pbb = new ProgressBarBuilder().setXXX().setYYY();
    ProgressBar.wrap(iterable, pbb)
  7. Customize a progress bar using ProgressBarBuilder

    main

    Since version 0.7.0, you can use the builder pattern to configure a ProgressBar instead of using standard constructors. This allows for fine-grained control over the visual style, units, task names, and update frequency. All configuration methods are optional.

    To use the builder, call ProgressBar.builder() and chain the desired configuration methods. Once configured, pass the builder instance to ProgressBar.wrap(collection, pbb) to wrap an iterable collection with the progress bar.

    ProgressBarBuilder pbb = ProgressBar.builder()
        .setInitialMax(<initial max>)
        .setStyle(ProgressBarStyle.<style>)
        .setTaskName(<taskName name>)
        .setUnit(<unit name>, <unit size>)
        .setUpdateIntervalMillis(<update interval>)
        .setMaxRenderedLength(<max rendered length in terminal>)
        .showSpeed()
        // or .showSpeed(new DecimalFormat("#.##")) to customize speed display
        .setEtaFunction(state -> ...)
      // This function is of type `ProgressState -> Optional<Duration>` 
      // that should output the estimated ETA of the progress.
      // Returning `Optional.empty()` means that ETA is not available.
    
    for (T x : ProgressBar.wrap(collection, pbb)) {
        ...
    }
  8. Use imperative progress bar control

    main

    For more granular control, use the ProgressBar class within a try-with-resources block. This ensures the progress bar stops automatically when the block completes.

    Key methods include:

    • step(): Increments progress by 1.
    • stepBy(n): Increments progress by n.
    • stepTo(n): Sets progress directly to n.
    • maxHint(n): Resets the maximum value. Setting n to a value less than zero makes the progress bar indefinite (unknown max).
    • setExtraMessage(String): Sets a message to display at the end of the bar.

    Note on Fonts: For fonts like Consolas or Andale Mono that do not align box-drawing glyphs properly, use ProgressBarStyle.ASCII in the constructor: new ProgressBar("Test", 100, ProgressBarStyle.ASCII).

    // try-with-resource block
    try (ProgressBar pb = new ProgressBar("Test", 100)) { // name, initial max
     // Use ProgressBar("Test", 100, ProgressBarStyle.ASCII) if you want ASCII output style
      for ( /* TASK TO TRACK */ ) {
        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
      }
    } // progress bar stops automatically after completion of try-with-resource block
  9. Select a predefined visual style

    main

    You can choose from three built-in visual style sets for your progress bar using the setStyle method on a ProgressBarBuilder.

    • ProgressBarStyle.COLORFUL_UNICODE_BLOCK (default): Uses Unicode box drawing symbols and ANSI colors. Recommended for fonts like Menlo, Fira Mono, Source Code Pro, or SF Mono in terminals that support ANSI colors.
    • ProgressBarStyle.UNICODE_BLOCK: Uses Unicode box drawing symbols without ANSI colors.
    • ProgressBarStyle.ASCII: Uses pure ASCII symbols. Recommended for fonts like Consolas or Andale Mono.
    ProgressBarBuilder pbb = new ProgressBarBuilder()
        .setStyle(ProgressBarStyle.COLORFUL_UNICODE_BLOCK);
  10. Manage multiple progress bars for parallel jobs

    main

    You can track multiple concurrent tasks by initializing multiple ProgressBar instances within a single try-with-resources block.

    try (ProgressBar pb1 = new ProgressBar("Job1", max1); 
         ProgressBar pb2 = new ProgressBar("Job2", max2)) {
         // ...
    }
  11. Track progress of Java collections and streams

    main

    You can wrap collections or streams to automatically set the progress bar's maximum value if the size is known. If the size is unknown, the progress bar will run in an indefinite mode.

    Traversing a collection:

    for (T x : ProgressBar.wrap(collection, "Traversing")) {
        // ...
    }

    Tracking parallel or sequential Java streams (version 0.7.2+):

    ProgressBar.wrap(IntStream.range(left, right).parallel(), "Task").forEach(i -> {
        // ...
    });
    ProgressBar.wrap(IntStream.range(left, right).parallel(), "Task").forEach(i -> {
            ...
        });
  12. Use declarative progress bar monitoring

    main

    You can automatically monitor progress by wrapping a collection using ProgressBar.wrap(collection, "TaskName"). This is useful for simple loops where the progress is directly tied to the number of items in a collection.

    // Looping over a collection:
    for (T x : ProgressBar.wrap(collection, "TaskName")) {
        // ...
        // Progress will be automatically monitored by a progress bar
    }