Java DefaultPrettyPrinter-class And Method Code Example


Here is an example of how to use the DefaultPrettyPrinter class from the org.apache.commons.io package in Java:

import org.apache.commons.io.output.DefaultPrettyPrinter;
import org.apache.commons.io.output.PrettyPrintWriter;

public class Main {
    public static void main(String[] args) {
        // Create a DefaultPrettyPrinter object
        DefaultPrettyPrinter printer = new DefaultPrettyPrinter();

        // Set the number of spaces per level of indentation
        printer.indentBy("  ");

        // Create a PrettyPrintWriter object
        PrettyPrintWriter writer = new PrettyPrintWriter(System.out, printer);

        // Write some indented text
        writer.println("This is an indented line.");
        writer.println("This is another indented line.");
        writer.println("This is a non-indented line.");
        writer.indent();
        writer.println("This is an indented line.");
        writer.println("This is another indented line.");
        writer.unindent();
        writer.println("This is a non-indented line.");

        // Close the writer
        writer.close();
    }
}

In this example, we create a DefaultPrettyPrinter object and set the number of spaces per level of indentation with the indentBy() method. Then we create a PrettyPrintWriter object that writes to the standard output and uses the DefaultPrettyPrinter. Then we write several lines of text using the println() method and indent/unindent using the indent() and unindent() methods of PrettyPrintWriter.

It's worth noting that this class was removed from the apache.commons.io library in version 2.6 and later versions, you can use other libraries like StringJoiner and StringBuilder to achieve similar functionality.