KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > nutch > fs > NFSDataOutputStream


1 /* Copyright (c) 2004 The Nutch Organization. All rights reserved. */
2 /* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
3 package net.nutch.fs;
4
5 import java.io.*;
6 import net.nutch.util.NutchConf;
7
8 /** Utility that wraps a {@link NFSOutputStream} in a {@link DataOutputStream}
9  * and buffers output through a {@link BufferedOutputStream}. */

10 public class NFSDataOutputStream extends DataOutputStream {
11   
12   private static class PositionCache extends FilterOutputStream {
13     long position;
14
15     public PositionCache(NFSOutputStream out) throws IOException {
16       super(out);
17       this.position = out.getPos();
18     }
19
20     // This is the only write() method called by BufferedOutputStream, so we
21
// trap calls to it in order to cache the position.
22
public void write(byte b[], int off, int len) throws IOException {
23       out.write(b, off, len);
24       position += len; // update position
25
}
26       
27     public long getPos() throws IOException {
28       return position; // return cached position
29
}
30     
31   }
32
33   private static class Buffer extends BufferedOutputStream {
34     public Buffer(PositionCache out, int bufferSize) throws IOException {
35       super(out, bufferSize);
36     }
37
38     public long getPos() throws IOException {
39       return ((PositionCache)out).getPos() + this.count;
40     }
41
42     // optimized version of write(int)
43
public void write(int b) throws IOException {
44       if (count >= buf.length) {
45         super.write(b);
46       } else {
47         buf[count++] = (byte)b;
48       }
49     }
50
51   }
52
53   public NFSDataOutputStream(NFSOutputStream out) throws IOException {
54     this(out, NutchConf.getInt("io.file.buffer.size", 4096));
55   }
56
57   public NFSDataOutputStream(NFSOutputStream out, int bufferSize)
58     throws IOException {
59     super(new Buffer(new PositionCache(out), bufferSize));
60   }
61
62   public long getPos() throws IOException {
63     return ((Buffer)out).getPos();
64   }
65
66 }
67
Popular Tags