1 package org.apache.lucene.store; 2 3 18 19 import java.io.IOException ; 20 21 22 public abstract class BufferedIndexOutput extends IndexOutput { 23 static final int BUFFER_SIZE = 1024; 24 25 private final byte[] buffer = new byte[BUFFER_SIZE]; 26 private long bufferStart = 0; private int bufferPosition = 0; 29 32 public void writeByte(byte b) throws IOException { 33 if (bufferPosition >= BUFFER_SIZE) 34 flush(); 35 buffer[bufferPosition++] = b; 36 } 37 38 43 public void writeBytes(byte[] b, int length) throws IOException { 44 int bytesLeft = BUFFER_SIZE - bufferPosition; 45 if (bytesLeft >= length) { 47 System.arraycopy(b, 0, buffer, bufferPosition, length); 49 bufferPosition += length; 50 if (BUFFER_SIZE - bufferPosition == 0) 52 flush(); 53 } else { 54 if (length > BUFFER_SIZE) { 56 if (bufferPosition > 0) 58 flush(); 59 flushBuffer(b, length); 61 bufferStart += length; 62 } else { 63 int pos = 0; int pieceLength; 66 while (pos < length) { 67 pieceLength = (length - pos < bytesLeft) ? length - pos : bytesLeft; 68 System.arraycopy(b, pos, buffer, bufferPosition, pieceLength); 69 pos += pieceLength; 70 bufferPosition += pieceLength; 71 bytesLeft = BUFFER_SIZE - bufferPosition; 73 if (bytesLeft == 0) { 74 flush(); 75 bytesLeft = BUFFER_SIZE; 76 } 77 } 78 } 79 } 80 } 81 82 83 public void flush() throws IOException { 84 flushBuffer(buffer, bufferPosition); 85 bufferStart += bufferPosition; 86 bufferPosition = 0; 87 } 88 89 94 protected abstract void flushBuffer(byte[] b, int len) throws IOException ; 95 96 97 public void close() throws IOException { 98 flush(); 99 } 100 101 105 public long getFilePointer() { 106 return bufferStart + bufferPosition; 107 } 108 109 112 public void seek(long pos) throws IOException { 113 flush(); 114 bufferStart = pos; 115 } 116 117 118 public abstract long length() throws IOException ; 119 120 121 } 122 | Popular Tags |