1 6 21 22 package de.schlichtherle.io.rof; 23 24 import java.io.EOFException ; 25 import java.io.File ; 26 import java.io.FileNotFoundException ; 27 import java.io.IOException ; 28 import java.io.RandomAccessFile ; 29 import java.nio.BufferUnderflowException ; 30 import java.nio.ByteBuffer ; 31 import java.nio.MappedByteBuffer ; 32 import java.nio.channels.FileChannel ; 33 34 39 public class ChannelReadOnlyFile implements ReadOnlyFile { 40 41 protected final FileChannel channel; 42 43 public ChannelReadOnlyFile(File file) throws FileNotFoundException { 44 channel = new RandomAccessFile (file, "r").getChannel(); 45 } 46 47 public long length() throws IOException { 48 return channel.size(); 49 } 50 51 public long getFilePointer() throws IOException { 52 return channel.position(); 53 } 54 55 public void seek(final long pos) throws IOException { 56 channel.position(pos); 57 } 58 59 60 private final ByteBuffer singleByteBuffer = ByteBuffer.allocate(1); 61 62 public int read() throws IOException { 63 if (channel.read(singleByteBuffer) == 1) 64 return singleByteBuffer.array()[0] & 0xFF; 65 else 66 return -1; 67 } 68 69 public final int read(byte b[]) throws IOException { 70 return read(b, 0, b.length); 71 } 72 73 public int read(final byte[] buf, final int off, final int len) 74 throws IOException { 75 return channel.read(ByteBuffer.wrap(buf, off, len)); 76 } 77 78 public void readFully(byte[] b) throws IOException { 79 readFully(b, 0, b.length); 80 } 81 82 public void readFully(byte[] buf, int off, int len) throws IOException { 83 int n = 0; 84 do { 85 int count = read(buf, off + n, len - n); 86 if (count < 0) 87 throw new EOFException (); 88 n += count; 89 } while (n < len); 90 } 91 92 public int skipBytes(int n) throws IOException { 93 if (n <= 0) 94 return 0; 96 final long pos = channel.position(); 97 final long len = channel.size(); 98 long newPos = pos + n; 99 if (newPos > len) 100 newPos = len; 101 channel.position(newPos); 102 103 return (int) (newPos - pos); 104 } 105 106 public void close() throws IOException { 107 channel.close(); 108 } 109 } 110 | Popular Tags |