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

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

There is a newer version: 2.1.5
Show newest version
package net.dongliu.commons.lang;

import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Collection;

/**
 * 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) { Printer printer = Printer.defaultPrinter; printer.println(params); return printer; } /** * print collection */ public static Printer println(Collection params) { Printer printer = Printer.defaultPrinter; printer.println(params); return printer; } /** * create new custom printer * * @return */ public static Printer.Builder printer() { return Printer.newBuilder(); } public static class Printer { private final String separator; private final String end; private final PrintStream out; public Printer(String separator, String end, PrintStream out) { this.separator = separator; this.end = end; this.out = out; } private static Printer defaultPrinter = newBuilder().build(); /** * print parameters */ public Printer println(Object... params) { for (int i = 0; i < params.length; i++) { out.print(params[i]); if (i != params.length - 1) { out.print(separator); } else { out.print(end); } } return this; } /** * print collections */ public Printer println(Collection params) { int i = 0; for (T param : params) { out.print(param); if (i++ != params.size() - 1) { out.print(separator); } else { out.print(end); } } return this; } private static Builder newBuilder() { return new Builder(); } public static class Builder { private String separator = " "; private String end = "\n"; private PrintStream out = System.out; /** * set separator. 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 println(Object... params) { Printer printer = this.build(); printer.println(params); return printer; } public Printer println(Collection params) { Printer printer = this.build(); printer.println(params); return printer; } } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy