All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.lang.IO Maven / Gradle / Ivy

package net.dongliu.commons.lang;

import java.io.OutputStream;
import java.io.PrintStream;

/**
 * utils method do to output and input.
 * Examples:
 * 
{@code
 *     IO.println("test").println("another test");
 *     IO.printer().sep(" -- ").end("-\n").println(1, 2, "test1").println("test");
 * }
 * 
* * @author Dong Liu */ public class IO { /** * print parameters */ public static Printer println(Object... params) { return Printer.defaultPrinter.println(params); } /** * print parameters */ public static Printer print(Object... params) { return Printer.defaultPrinter.print(params); } /** * create new custom printer * * @return */ public static Printer.Builder printer() { return Printer.newBuilder(); } public static class Printer { private final String sep; private final String end; private final PrintStream out; public Printer(String sep, String end, PrintStream out) { this.sep = sep; this.end = end; this.out = out; } private static Printer defaultPrinter = newBuilder().build(); /** * print parameters, without line end */ public Printer print(Object... params) { _print(params, false); return this; } /** * print parameters */ public Printer println(Object... params) { _print(params, true); return this; } private void _print(T[] params, boolean printEnd) { int i = 0; for (T param : params) { out.print(param); if (i++ != params.length - 1) { out.print(sep); } else if (printEnd) { out.print(end); } } } private static Builder newBuilder() { return new Builder(); } public static class Builder { private String separator = " "; private String end = "\n"; private PrintStream out = System.out; /** * set sep. default " " */ public Builder sep(String delimiter) { this.separator = delimiter; return this; } /** * set line end. default "\n" */ public Builder end(String end) { this.end = end; return this; } /** * set output. default System.out */ public Builder out(PrintStream out) { this.out = out; return this; } /** * set output. default System.out */ public Builder out(OutputStream out) { this.out = new PrintStream(out); return this; } public Printer build() { return new Printer(separator, end, out); } public Printer print(Object... params) { return this.build().print(params); } public Printer println(Object... params) { return this.build().println(params); } } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy