KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > io > StringOutputStream


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

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

14 public class StringOutputStream extends OutputStream JavaDoc implements Serializable JavaDoc {
15     
16     /**
17      * The internal destination StringBuffer.
18      */

19     protected StringBuffer JavaDoc buf = null;
20
21     /**
22      * Creates new StringOutputStream, makes a new internal StringBuffer.
23      */

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

35     public String JavaDoc toString() {
36         return buf.toString();
37     }
38
39     /**
40     * Sets the internal StringBuffer to null.
41     */

42     public void close() {
43         buf = null;
44
45     }
46
47     /**
48      * Writes and appends byte array to StringOutputStream.
49      *
50      * @param b byte array
51      */

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

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

80     public void write(int b) {
81         buf.append((char)b);
82     }
83 }
84
85
86
Popular Tags