1 /* $Id: CodePrintString.java 1 2010-02-24 13:03:05Z haidw $ */
5 * Class to print code that is correctly indented.
7 public class CodePrintString {
10 * Default constructor.
12 * @param stringBuffer string buffer where the result is stored
14 public CodePrintString(StringBuffer stringBuffer) {
19 * Print a line without indentation.
21 public void print(String string) {
26 * Add a line break to the current line. Results in an empty
27 * line if the current line is empty.
29 public void println() {
30 _code.append(System.getProperty("line.separator"));
34 * Print a line without indentation and add a line break.
35 * @param string string to print
37 public void println(String string) {
38 _code.append(string + System.getProperty("line.separator"));
42 * Print spaces according to current level of indentation.
44 public void printPrefix() {
45 _code.append(_prefix);
49 * Print a line at the current level of indentation.
50 * @param string string to print
52 public void printPrefix(String string) {
53 _code.append(_prefix + string);
57 * Print a line at the current level of indentation and a line break.
58 * @param string string to print
60 public void printPrefixln(String string) {
61 _code.append(_prefix + string
62 + System.getProperty("line.separator"));
66 * Print the opening tag for the given XML tag name and increase
68 * @param tagName name of the XML tag
70 public void printOpeningTag(String tagName) {
77 * Decrease the indentation and print the closing tag for the given
79 * @param tagName name of the XML tag
81 public void printClosingTag(String tagName) {
83 printPrefixln("</" + tagName + ">");
87 * Decrement the indentation.
89 public void prefixDec() {
90 if( _prefix.length() >= _offset.length() ) {
91 _prefix = _prefix.substring(_offset.length());
96 * Increment the indentation.
98 public void prefixInc() {
103 * Get the formatted output string.
104 * @return output string
106 public String toString() {
107 return _code.toString();
111 * Test the CodePrintString implementation.
113 public static void main(String[] args) {
114 StringBuffer buffer = new StringBuffer();
115 CodePrintString ps = new CodePrintString(buffer);
116 ps.printOpeningTag("tag");
118 ps.printPrefixln("<abc/>");
119 ps.printClosingTag("tag");
120 System.out.println(ps.toString());
123 protected static String _offset = " ";
124 protected String _prefix = "";
125 protected StringBuffer _code = null;