1 package org.apache.lucene.store; 2 3 18 19 import java.io.IOException ; 20 21 26 27 public class RAMOutputStream extends BufferedIndexOutput { 28 private RAMFile file; 29 private int pointer = 0; 30 31 32 public RAMOutputStream() { 33 this(new RAMFile()); 34 } 35 36 RAMOutputStream(RAMFile f) { 37 file = f; 38 } 39 40 41 public void writeTo(IndexOutput out) throws IOException { 42 flush(); 43 final long end = file.length; 44 long pos = 0; 45 int buffer = 0; 46 while (pos < end) { 47 int length = BUFFER_SIZE; 48 long nextPos = pos + length; 49 if (nextPos > end) { length = (int)(end - pos); 51 } 52 out.writeBytes((byte[])file.buffers.elementAt(buffer++), length); 53 pos = nextPos; 54 } 55 } 56 57 58 public void reset() { 59 try { 60 seek(0); 61 } catch (IOException e) { throw new RuntimeException (e.toString()); 63 } 64 65 file.length = 0; 66 } 67 68 public void flushBuffer(byte[] src, int len) { 69 byte[] buffer; 70 int bufferPos = 0; 71 while (bufferPos != len) { 72 int bufferNumber = pointer/BUFFER_SIZE; 73 int bufferOffset = pointer%BUFFER_SIZE; 74 int bytesInBuffer = BUFFER_SIZE - bufferOffset; 75 int remainInSrcBuffer = len - bufferPos; 76 int bytesToCopy = bytesInBuffer >= remainInSrcBuffer ? remainInSrcBuffer : bytesInBuffer; 77 78 if (bufferNumber == file.buffers.size()) { 79 buffer = new byte[BUFFER_SIZE]; 80 file.buffers.addElement(buffer); 81 } else { 82 buffer = (byte[]) file.buffers.elementAt(bufferNumber); 83 } 84 85 System.arraycopy(src, bufferPos, buffer, bufferOffset, bytesToCopy); 86 bufferPos += bytesToCopy; 87 pointer += bytesToCopy; 88 } 89 90 if (pointer > file.length) 91 file.length = pointer; 92 93 file.lastModified = System.currentTimeMillis(); 94 } 95 96 public void close() throws IOException { 97 super.close(); 98 } 99 100 public void seek(long pos) throws IOException { 101 super.seek(pos); 102 pointer = (int)pos; 103 } 104 public long length() { 105 return file.length; 106 } 107 } 108 | Popular Tags |