1 49 package com.lowagie.text.pdf; 50 51 import java.io.FileInputStream ; 52 import java.io.FileNotFoundException ; 53 import java.io.IOException ; 54 import java.lang.reflect.Method ; 55 import java.nio.BufferUnderflowException ; 56 import java.nio.MappedByteBuffer ; 57 import java.nio.channels.FileChannel ; 58 import java.security.AccessController ; 59 import java.security.PrivilegedAction ; 60 61 67 public class MappedRandomAccessFile { 68 69 private MappedByteBuffer mappedByteBuffer = null; 70 private FileChannel channel = null; 71 72 79 public MappedRandomAccessFile(String filename, String mode) 80 throws FileNotFoundException , IOException { 81 82 if (mode.equals("rw")) 83 init( 84 new java.io.RandomAccessFile (filename, mode).getChannel(), 85 FileChannel.MapMode.READ_WRITE); 86 else 87 init( 88 new FileInputStream (filename).getChannel(), 89 FileChannel.MapMode.READ_ONLY); 90 91 } 92 93 99 private void init(FileChannel channel, FileChannel.MapMode mapMode) 100 throws IOException { 101 102 this.channel = channel; 103 this.mappedByteBuffer = channel.map(mapMode, 0L, channel.size()); 104 mappedByteBuffer.load(); 105 } 106 107 111 public int read() { 112 try { 113 byte b = mappedByteBuffer.get(); 114 int n = b & 0xff; 115 116 return n; 117 } catch (BufferUnderflowException e) { 118 return -1; } 120 } 121 122 129 public int read(byte bytes[], int off, int len) { 130 int pos = mappedByteBuffer.position(); 131 int limit = mappedByteBuffer.limit(); 132 if (pos == limit) 133 return -1; int newlimit = pos + len - off; 135 if (newlimit > limit) { 136 len = limit - pos; } 138 mappedByteBuffer.get(bytes, off, len); 139 return len; 140 } 141 142 146 public long getFilePointer() { 147 return mappedByteBuffer.position(); 148 } 149 150 154 public void seek(long pos) { 155 mappedByteBuffer.position((int) pos); 156 } 157 158 162 public long length() { 163 return mappedByteBuffer.limit(); 164 } 165 166 170 public void close() throws IOException { 171 clean(mappedByteBuffer); 172 mappedByteBuffer = null; 173 if (channel != null) 174 channel.close(); 175 channel = null; 176 } 177 178 182 protected void finalize() throws Throwable { 183 close(); 184 super.finalize(); 185 } 186 187 192 public static boolean clean(final java.nio.ByteBuffer buffer) { 193 if (buffer == null || !buffer.isDirect()) 194 return false; 195 196 Boolean b = (Boolean ) AccessController.doPrivileged(new PrivilegedAction () { 197 public Object run() { 198 Boolean success = Boolean.FALSE; 199 try { 200 Method getCleanerMethod = buffer.getClass().getMethod("cleaner", null); 201 getCleanerMethod.setAccessible(true); 202 Object cleaner = getCleanerMethod.invoke(buffer, null); 203 Method clean = cleaner.getClass().getMethod("clean", null); 204 clean.invoke(cleaner, null); 205 success = Boolean.TRUE; 206 } catch (Exception e) { 207 } 210 return success; 211 } 212 }); 213 214 return b.booleanValue(); 215 } 216 217 } 218 | Popular Tags |