View Javadoc

1   package cz.cuni.amis.utils;
2   
3   import java.io.OutputStream;
4   import java.io.Serializable;
5   
6   /**
7    * OutputStream for the String, writes to StringBuffer.
8    * <p><p>
9    * Based on: http://kickjava.com/src/jodd/util/StringOutputStream.java.htm
10   * Thank you!
11   */
12  public class StringOutputStream extends OutputStream implements Serializable {
13  
14  	/**
15  	 * The internal destination StringBuffer.
16  	 */
17  	private StringBuffer buffer = null;
18  	
19  	private String resultString = null;
20  
21  	/**
22  	 * Creates new StringOutputStream, makes a new internal StringBuffer.
23  	 */
24  	public StringOutputStream() {
25  		super();
26  		buffer = new StringBuffer();
27  	}
28  
29  	/**
30  	 * Returns string from the underlying buffer
31  	 * @return
32  	 */
33  	public String getString() {
34  		if (resultString != null) return resultString;
35  		return buffer.toString();
36  		
37  	}
38  
39  	@Override
40  	public void close() {
41  		resultString = buffer.toString();
42  		buffer = null;
43  	}
44  
45  	@Override
46  	public void write(byte[] b) {
47  		buffer.append(toCharArray(b));
48  	}
49  
50  	private char[] toCharArray(byte[] barr) {
51  		if (barr == null) {
52  			return null;
53  		}
54  		char[] carr = new char[barr.length];
55  		for (int i = 0; i < barr.length; i++) {
56  			carr[i] = (char) barr[i];
57  		}
58  		return carr;
59  	}
60  
61  	@Override
62  	public void write(byte[] b, int off, int len) {
63  		if ((off < 0) || (len < 0) || (off + len) > b.length) {
64  			throw new IndexOutOfBoundsException("StringOutputStream.write: Parameters out of bounds.");
65  		}
66  		byte[] bytes = new byte[len];
67  		for (int i = 0; i < len; i++) {
68  			bytes[i] = b[off];
69  			off++;
70  		}
71  		buffer.append(toCharArray(bytes));
72  	}
73  
74  	@Override
75  	public void write(int b) {
76  		buffer.append((char) b);
77  	}
78  
79  }