| 1 31 package org.pdfbox.io; 32 33 import java.io.IOException ; 34 import java.util.Arrays ; 35 36 42 public class RandomAccessBuffer implements RandomAccess 43 { 44 45 private static final int EXTRA_SPACE = 16384; private byte[] buffer; 47 private long pointer; 48 private long size; 49 50 53 public RandomAccessBuffer() 54 { 55 buffer = new byte[EXTRA_SPACE]; 56 pointer = 0; 57 size = EXTRA_SPACE; 58 } 59 60 63 public void close() throws IOException 64 { 65 buffer = null; 66 pointer = 0; 67 size = 0; 68 } 69 70 73 public void seek(long position) throws IOException 74 { 75 this.pointer = position; 76 } 77 78 81 public int read() throws IOException 82 { 83 if (pointer >= this.size) 84 { 85 return -1; 86 } 87 int result = buffer[(int)pointer]; 88 pointer++; 89 return result; 90 } 91 92 95 public int read(byte[] b, int offset, int length) throws IOException 96 { 97 if (pointer >= this.size) 98 { 99 return 0; 100 } 101 int maxLength = (int) Math.min(length, this.size-pointer); 102 System.arraycopy(buffer, (int) pointer, b, offset, maxLength); 103 pointer += maxLength; 104 return maxLength; 105 } 106 107 110 public long length() throws IOException 111 { 112 return size; 113 } 114 115 118 public void write(int b) throws IOException 119 { 120 write(new byte[] {(byte) b}, 0, 1); 121 } 122 123 126 public void write(byte[] b, int offset, int length) throws IOException 127 { 128 if (pointer+length >= buffer.length) 129 { 130 byte[] temp = new byte[buffer.length+length+EXTRA_SPACE]; 132 Arrays.fill(temp, (byte)0); 133 System.arraycopy(buffer, 0, temp, 0, (int) this.size); 134 buffer = temp; 135 } 136 System.arraycopy(b, offset, buffer, (int)pointer, length); 137 pointer += length; 138 if (pointer > this.size) 139 { 140 this.size = pointer; 141 } 142 } 143 } 144 | Popular Tags |