| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package uk.me.parabola.imgfmt.sys; |
| 18 |
|
| 19 |
import java.io.FileNotFoundException; |
| 20 |
import java.io.IOException; |
| 21 |
import java.io.RandomAccessFile; |
| 22 |
import java.nio.ByteBuffer; |
| 23 |
import java.nio.channels.FileChannel; |
| 24 |
|
| 25 |
import uk.me.parabola.imgfmt.ReadFailedException; |
| 26 |
import uk.me.parabola.imgfmt.fs.ImgChannel; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
public class FileImgChannel implements ImgChannel { |
| 35 |
private final FileChannel channel; |
| 36 |
private long position; |
| 37 |
|
| 38 |
public FileImgChannel(String filename, String mode) { |
| 39 |
RandomAccessFile raf; |
| 40 |
try { |
| 41 |
raf = new RandomAccessFile(filename, mode); |
| 42 |
} catch (FileNotFoundException e) { |
| 43 |
throw new ReadFailedException("Could not open " + filename, e); |
| 44 |
} |
| 45 |
this.channel = raf.getChannel(); |
| 46 |
} |
| 47 |
|
| 48 |
public FileImgChannel(FileChannel channel) { |
| 49 |
this.channel = channel; |
| 50 |
} |
| 51 |
|
| 52 |
public int read(ByteBuffer dst) throws IOException { |
| 53 |
int n = channel.read(dst); |
| 54 |
if (n > 0) |
| 55 |
position += n; |
| 56 |
return n; |
| 57 |
} |
| 58 |
|
| 59 |
public boolean isOpen() { |
| 60 |
return channel.isOpen(); |
| 61 |
} |
| 62 |
|
| 63 |
public void close() throws IOException { |
| 64 |
channel.close(); |
| 65 |
} |
| 66 |
|
| 67 |
public int write(ByteBuffer src) throws IOException { |
| 68 |
int n = channel.write(src); |
| 69 |
position += n; |
| 70 |
return n; |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
public long position() { |
| 81 |
return position; |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
public void position(long pos) { |
| 90 |
try { |
| 91 |
channel.position(pos); |
| 92 |
position = pos; |
| 93 |
} catch (IOException e) { |
| 94 |
throw new ReadFailedException("Could not seek", e); |
| 95 |
} |
| 96 |
} |
| 97 |
} |