1 package cz.cuni.amis.utils;
2
3 import java.io.OutputStream;
4 import java.io.Serializable;
5
6
7
8
9
10
11
12 public class StringOutputStream extends OutputStream implements Serializable {
13
14
15
16
17 private StringBuffer buffer = null;
18
19 private String resultString = null;
20
21
22
23
24 public StringOutputStream() {
25 super();
26 buffer = new StringBuffer();
27 }
28
29
30
31
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 }