1 14 package org.wings.io; 15 16 import java.io.IOException ; 17 18 25 public final class DeviceBuffer implements Device { 26 28 private byte[] buffer; 29 30 private int position = 0; 31 32 private int capacityIncrement; 33 34 public DeviceBuffer(int initialCapacity, int capacityIncrement) { 35 buffer = new byte[initialCapacity]; 36 this.capacityIncrement = capacityIncrement; 37 } 38 39 public boolean isSizePreserving() { return true; } 40 41 42 public DeviceBuffer(int initialCapacity) { 43 this(initialCapacity, -1); 44 } 45 46 47 public DeviceBuffer() { 48 this(2000); 49 } 50 51 public void flush() { } 52 53 public void close() { } 54 55 58 public Device print(String s) throws IOException { 59 60 if (s == null) 61 return print("null"); 62 63 int len = s.length(); 64 for (int i = 0; i < len; i++) { 65 write((byte) s.charAt(i)); 72 } 73 return this; 74 75 83 } 84 85 88 public Device print(char[] c) throws IOException { 89 return print(c, 0, c.length - 1); 90 } 91 92 95 public Device print(char[] c, int start, int len) throws IOException { 96 final int end = start + len; 97 for (int i = start; i < end; i++) 98 print(c[i]); 99 return this; 100 } 101 102 105 public Device print(int i) throws IOException { 106 return print(String.valueOf(i)); 107 } 108 109 112 public Device print(Object o) throws IOException { 113 if (o != null) 114 return print(o.toString()); 115 else 116 return print("null"); 117 } 118 119 122 public Device print(char c) throws IOException { 123 return print(String.valueOf(c)); 124 } 125 126 129 public Device write(int c) throws IOException { 130 return print(String.valueOf(c)); 131 } 132 133 139 public Device write(byte b) throws IOException { 140 while (position + 1 > buffer.length) 141 incrementCapacity(); 142 buffer[position++] = b; 143 return this; 144 } 145 146 150 public Device write(byte b[]) throws IOException { 151 return write(b, 0, b.length); 152 } 153 154 155 public void clear() { 156 position = 0; 157 } 158 159 private void incrementCapacity() { 160 byte[] oldBuffer = buffer; 161 162 int newCapacity = (capacityIncrement > 0) ? 163 (buffer.length + capacityIncrement) : (buffer.length * 2); 164 165 buffer = new byte[newCapacity]; 166 System.arraycopy(oldBuffer, 0, buffer, 0, position); 167 } 168 169 173 public Device write(byte b[], int off, int len) throws IOException { 174 while (position + len > buffer.length) 175 incrementCapacity(); 176 177 System.arraycopy(b, off, buffer, position, len); 178 position += len; 179 180 return this; 181 } 182 183 184 public void writeTo(Device d) { 185 try { 186 d.write(buffer, 0, position); 187 } catch (IOException ignore) {} 188 } 189 } 190 191 192 | Popular Tags |