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: 1.0.9
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.
 * 

* println: * IO.println("test").println("another test"); * IO.sep(" -- ").end("$$\n").println(1, 2, "adsfa").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; } public static Printer println(Collection params) { Printer printer = Printer.defaultPrinter; printer.println(params); return printer; } /** * set separator. default " " */ public static Printer.Builder sep(String delimiter) { return Printer.newBuilder().sep(delimiter); } /** * set output. default System.out */ public static Printer.Builder out(OutputStream out) { return Printer.newBuilder().out(out); } /** * set output. default System.out */ public static Printer.Builder out(PrintStream out) { return Printer.newBuilder().out(out); } /** * set line end. default "\n" */ public static Printer.Builder end(String lineEnd) { return Printer.newBuilder().end(lineEnd); } 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(); 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; } 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; public Builder sep(String delimiter) { this.separator = delimiter; return this; } public Builder end(String end) { this.end = end; return this; } public Builder out(PrintStream out) { this.out = out; return this; } 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