1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.textclassifier.utils; 18 19 import com.google.common.base.Preconditions; 20 import java.io.PrintWriter; 21 22 /** 23 * A print writer that supports indentation. 24 * 25 * @see PrintWriter 26 */ 27 public final class IndentingPrintWriter { 28 static final String SINGLE_INDENT = " "; 29 30 private final PrintWriter writer; 31 private final StringBuilder indentBuilder = new StringBuilder(); 32 private String currentIndent = ""; 33 IndentingPrintWriter(PrintWriter writer)34 public IndentingPrintWriter(PrintWriter writer) { 35 this.writer = Preconditions.checkNotNull(writer); 36 } 37 38 /** Prints a string. */ println(String string)39 public IndentingPrintWriter println(String string) { 40 writer.print(currentIndent); 41 writer.print(string); 42 writer.println(); 43 return this; 44 } 45 46 /** Prints a empty line */ println()47 public IndentingPrintWriter println() { 48 writer.println(); 49 return this; 50 } 51 52 /** Increases indents for subsequent texts. */ increaseIndent()53 public IndentingPrintWriter increaseIndent() { 54 indentBuilder.append(SINGLE_INDENT); 55 currentIndent = indentBuilder.toString(); 56 return this; 57 } 58 59 /** Decreases indents for subsequent texts. */ decreaseIndent()60 public IndentingPrintWriter decreaseIndent() { 61 indentBuilder.delete(0, SINGLE_INDENT.length()); 62 currentIndent = indentBuilder.toString(); 63 return this; 64 } 65 66 /** Prints a key-valued pair. */ printPair(String key, Object value)67 public IndentingPrintWriter printPair(String key, Object value) { 68 println(String.format("%s=%s", key, String.valueOf(value))); 69 return this; 70 } 71 72 /** Flushes the stream. */ flush()73 public void flush() { 74 writer.flush(); 75 } 76 } 77