01: /*
02: * Copyright (C) 2004, 2005, 2006 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 07. March 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.core.util;
13:
14: import com.thoughtworks.xstream.io.StreamException;
15:
16: import java.io.IOException;
17: import java.io.Writer;
18:
19: public class QuickWriter {
20:
21: private final Writer writer;
22: private char[] buffer;
23: private int pointer;
24:
25: public QuickWriter(Writer writer) {
26: this (writer, 1024);
27: }
28:
29: public QuickWriter(Writer writer, int bufferSize) {
30: this .writer = writer;
31: buffer = new char[bufferSize];
32: }
33:
34: public void write(String str) {
35: int len = str.length();
36: if (pointer + len >= buffer.length) {
37: flush();
38: if (len > buffer.length) {
39: raw(str.toCharArray());
40: return;
41: }
42: }
43: str.getChars(0, len, buffer, pointer);
44: pointer += len;
45: }
46:
47: public void write(char c) {
48: if (pointer + 1 >= buffer.length) {
49: flush();
50: }
51: buffer[pointer++] = c;
52: }
53:
54: public void write(char[] c) {
55: int len = c.length;
56: if (pointer + len >= buffer.length) {
57: flush();
58: if (len > buffer.length) {
59: raw(c);
60: return;
61: }
62: }
63: System.arraycopy(c, 0, buffer, pointer, len);
64: pointer += len;
65: }
66:
67: public void flush() {
68: try {
69: writer.write(buffer, 0, pointer);
70: pointer = 0;
71: writer.flush();
72: } catch (IOException e) {
73: throw new StreamException(e);
74: }
75: }
76:
77: public void close() {
78: try {
79: writer.write(buffer, 0, pointer);
80: pointer = 0;
81: writer.close();
82: } catch (IOException e) {
83: throw new StreamException(e);
84: }
85: }
86:
87: private void raw(char[] c) {
88: try {
89: writer.write(c);
90: writer.flush();
91: } catch (IOException e) {
92: throw new StreamException(e);
93: }
94: }
95: }
|