KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > core > util > QuickWriter


1 package com.thoughtworks.xstream.core.util;
2
3 import com.thoughtworks.xstream.io.StreamException;
4
5 import java.io.IOException JavaDoc;
6 import java.io.Writer JavaDoc;
7
8 public class QuickWriter {
9
10     private final Writer JavaDoc writer;
11     private char[] buffer;
12     private int pointer;
13
14     public QuickWriter(Writer JavaDoc writer) {
15         this.writer = writer;
16         buffer = new char[32];
17     }
18
19     public QuickWriter(Writer JavaDoc writer, int bufferSize) {
20         this.writer = writer;
21         buffer = new char[bufferSize];
22     }
23
24     public void write(String JavaDoc str) {
25         int len = str.length();
26         if (pointer + len >= buffer.length) {
27             flush();
28             if (len > buffer.length) {
29                 raw(str.toCharArray());
30                 return;
31             }
32         }
33         str.getChars(0, len, buffer, pointer);
34         pointer += len;
35     }
36
37     public void write(char c) {
38         if (pointer + 1 >= buffer.length) {
39             flush();
40         }
41         buffer[pointer++] = c;
42     }
43
44     public void write(char[] c) {
45         int len = c.length;
46         if (pointer + len >= buffer.length) {
47             flush();
48             if (len > buffer.length) {
49                 raw(c);
50                 return;
51             }
52         }
53         System.arraycopy(c, 0, buffer, pointer, len);
54         pointer += len;
55     }
56
57     public void flush() {
58         try {
59             writer.write(buffer, 0, pointer);
60             pointer = 0;
61             writer.flush();
62         } catch (IOException JavaDoc e) {
63             throw new StreamException(e);
64         }
65     }
66
67     private void raw(char[] c) {
68         try {
69             writer.write(c);
70             writer.flush();
71         } catch (IOException JavaDoc e) {
72             throw new StreamException(e);
73         }
74     }
75 }
76
Popular Tags