KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > mapping > CharArrayOutPort


1 package gnu.mapping;
2 import gnu.lists.Consumer;
3 import java.io.PrintWriter JavaDoc;
4
5 /**
6  * Similar to CharArrayWriter.
7  */

8
9 public class CharArrayOutPort extends OutPort
10 {
11   public CharArrayOutPort()
12   {
13     super(null, false, "<string>");
14   }
15
16   public int length ()
17   {
18     return bout.bufferFillPointer;
19   }
20
21   public void setLength (int length)
22   {
23     bout.bufferFillPointer = length;
24   }
25
26   public void reset ()
27   {
28     bout.bufferFillPointer = 0;
29   }
30
31   /** Returns the written data as a freshly copied {@code char} array. */
32   public char[] toCharArray()
33   {
34     int length = bout.bufferFillPointer;
35     char[] result = new char[length];
36     System.arraycopy(bout.buffer, 0, result, 0, length);
37     return result;
38   }
39
40   /** Do nothing.
41    * This allows access to the buffer after the port is closed.
42    * Not clear whether this is a good or bad idea, but it matches
43    * ByteArrayOutputStream, CharArrayWriter, and StringWriter.
44    */

45   public void close ()
46   {
47   }
48
49   /** No point in registering this port with a WriterManager. */
50   protected boolean closeOnExit ()
51   {
52     return false;
53   }
54
55   /** Returns the written data as a new {@code String}. */
56   public String JavaDoc toString ()
57   {
58     return new String JavaDoc(bout.buffer, 0, bout.bufferFillPointer);
59   }
60
61   /** Returns a substring of the written data as a new {@code String}.
62    * Equivalent to {@code toString().substring(beginIndex, endIndex)}
63    * but more efficient.
64    */

65   public String JavaDoc toSubString (int beginIndex, int endIndex)
66   {
67     if (endIndex > bout.bufferFillPointer)
68       throw new IndexOutOfBoundsException JavaDoc();
69     return new String JavaDoc(bout.buffer, beginIndex, endIndex - beginIndex);
70   }
71
72   /** Returns a substring of the written data as a new {@code String}.
73    * Equivalent to {@code toString().substring(beginIndex)}
74    * but more efficient.
75    */

76   public String JavaDoc toSubString (int beginIndex)
77   {
78     return new String JavaDoc(bout.buffer, beginIndex,
79                       bout.bufferFillPointer - beginIndex);
80   }
81
82   public void writeTo (Consumer out)
83   {
84     out.write(bout.buffer, 0, bout.bufferFillPointer);
85   }
86
87   public void writeTo (int start, int count, Consumer out)
88   {
89     out.write(bout.buffer, start, count);
90   }
91 }
92
93
Popular Tags