KickJava   Java API By Example, From Geeks To Geeks.

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


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
9 /** A reusable {@link DataInput} implementation that reads from an in-memory
10  * buffer.
11  *
12  * <p>This saves memory over creating a new DataInputStream and
13  * ByteArrayInputStream each time data is read.
14  *
15  * <p>Typical usage is something like the following:<pre>
16  *
17  * DataInputBuffer buffer = new DataInputBuffer();
18  * while (... loop condition ...) {
19  * byte[] data = ... get data ...;
20  * int dataLength = ... get data length ...;
21  * buffer.reset(data, dataLength);
22  * ... read buffer using DataInput methods ...
23  * }
24  * </pre>
25  *
26  * @author Doug Cutting
27  */

28 public class DataInputBuffer extends DataInputStream {
29
30   private static class Buffer extends ByteArrayInputStream {
31     public Buffer() {
32       super(new byte[] {});
33     }
34
35     public void reset(byte[] input, int start, int length) {
36       this.buf = input;
37       this.count = start+length;
38       this.mark = start;
39       this.pos = start;
40     }
41
42     public int getPosition() { return pos; }
43   }
44
45   private Buffer buffer;
46   
47   /** Constructs a new empty buffer. */
48   public DataInputBuffer() {
49     this(new Buffer());
50   }
51
52   private DataInputBuffer(Buffer buffer) {
53     super(buffer);
54     this.buffer = buffer;
55   }
56
57   /** Resets the data that the buffer reads. */
58   public void reset(byte[] input, int length) {
59     buffer.reset(input, 0, length);
60   }
61
62   /** Resets the data that the buffer reads. */
63   public void reset(byte[] input, int start, int length) {
64     buffer.reset(input, start, length);
65   }
66
67   /** Returns the current position in the input. */
68   public int getPosition() { return buffer.getPosition(); }
69
70 }
71
Popular Tags