KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > StringOutputStream


1 package jodd.util;
2
3 import java.io.OutputStream;
4 import java.io.Serializable;
5
6 /**
7  * Provides an OutputStream to an internal String. Internally converts bytes
8  * to a Strings and stores them in an internal StringBuffer.
9  */

10 public class StringOutputStream extends OutputStream implements Serializable {
11     
12     /**
13      * The internal destination StringBuffer.
14      */

15     protected StringBuffer buf = null;
16
17     /**
18      * Creates new StringOutputStream, makes a new internal StringBuffer.
19      */

20     public StringOutputStream() {
21         super();
22         buf = new StringBuffer();
23     }
24
25     /**
26      * Returns the content of the internal StringBuffer as a String, the result
27      * of all writing to this OutputStream.
28      *
29      * @return returns the content of the internal StringBuffer
30      */

31     public String toString() {
32         return buf.toString();
33     }
34
35     /**
36     * Sets the internal StringBuffer to null.
37     */

38     public void close() {
39         buf = null;
40
41     }
42
43     /**
44      * Writes and appends byte array to StringOutputStream.
45      *
46      * @param b byte array
47      */

48     public void write(byte[] b) {
49         buf.append(CharUtil.toCharArray(b));
50     }
51
52     /**
53      * Writes and appends a byte array to StringOutputStream.
54      *
55      * @param b the byte array
56      * @param off the byte array starting index
57      * @param len the number of bytes from byte array to write to the stream
58      */

59     public void write(byte[] b, int off, int len) {
60         if ((off < 0) || (len < 0) || (off + len) > b.length) {
61             throw new IndexOutOfBoundsException("StringOutputStream.write: Parameters out of bounds.");
62         }
63         byte[] bytes = new byte[len];
64         for (int i = 0; i < len; i++) {
65             bytes[i] = b[off];
66             off++;
67         }
68         buf.append(CharUtil.toCharArray(bytes));
69     }
70
71     /**
72      * Writes and appends a single byte to StringOutputStream.
73      *
74      * @param b the byte as an int to add
75      */

76     public void write(int b) {
77         buf.append((char)b);
78     }
79 }
80
81
82
Popular Tags