KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > nutch > io > DataOutputBuffer


1 /* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
2 /* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
3
4 package net.nutch.io;
5
6 import java.io.*;
7
8 /** A reusable {@link DataOutput} implementation that writes to an in-memory
9  * buffer.
10  *
11  * <p>This saves memory over creating a new DataOutputStream and
12  * ByteArrayOutputStream each time data is written.
13  *
14  * <p>Typical usage is something like the following:<pre>
15  *
16  * DataOutputBuffer buffer = new DataOutputBuffer();
17  * while (... loop condition ...) {
18  * buffer.reset();
19  * ... write buffer using DataOutput methods ...
20  * byte[] data = buffer.getData();
21  * int dataLength = buffer.getLength();
22  * ... write data to its ultimate destination ...
23  * }
24  * </pre>
25  *
26  * @author Doug Cutting
27  */

28 public class DataOutputBuffer extends DataOutputStream {
29
30   private static class Buffer extends ByteArrayOutputStream {
31     public byte[] getData() { return buf; }
32     public int getLength() { return count; }
33     public void reset() { count = 0; }
34
35     public void write(DataInput in, int len) throws IOException {
36       int newcount = count + len;
37       if (newcount > buf.length) {
38         byte newbuf[] = new byte[Math.max(buf.length << 1, newcount)];
39         System.arraycopy(buf, 0, newbuf, 0, count);
40         buf = newbuf;
41       }
42       in.readFully(buf, count, len);
43       count = newcount;
44     }
45   }
46
47   private Buffer buffer;
48   
49   /** Constructs a new empty buffer. */
50   public DataOutputBuffer() {
51     this(new Buffer());
52   }
53   
54   private DataOutputBuffer(Buffer buffer) {
55     super(buffer);
56     this.buffer = buffer;
57   }
58
59   /** Returns the current contents of the buffer.
60    * Data is only valid to {@link #getLength()}.
61    */

62   public byte[] getData() { return buffer.getData(); }
63
64   /** Returns the length of the valid data currently in the buffer. */
65   public int getLength() { return buffer.getLength(); }
66
67   /** Resets the buffer to empty. */
68   public DataOutputBuffer reset() {
69     this.written = 0;
70     buffer.reset();
71     return this;
72   }
73
74   /** Writes bytes from a DataInput directly into the buffer. */
75   public void write(DataInput in, int length) throws IOException {
76     buffer.write(in, length);
77   }
78 }
79
Popular Tags