Implement a rudimentary RandomAccessFile#getChannel

This implementation is by no means intended to be complete, just enough to
support running http://http://loci.wisc.edu/software/bio-formats's
loci.formats.tools.ImageConverter tool.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
This commit is contained in:
Johannes Schindelin 2013-10-17 14:50:43 -05:00
parent 3a67f81b50
commit 3681ae508e

View File

@ -11,6 +11,8 @@
package java.io;
import java.lang.IllegalArgumentException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class RandomAccessFile {
private long peer;
@ -147,4 +149,50 @@ public class RandomAccessFile {
}
private static native void close(long peer);
public FileChannel getChannel() {
return new FileChannel() {
public void close() {
if (peer != 0) RandomAccessFile.close(peer);
}
public boolean isOpen() {
return peer != 0;
}
public int read(ByteBuffer dst, long position) throws IOException {
if (!dst.hasArray()) throw new IOException("Cannot handle " + dst.getClass());
// TODO: this needs to be synchronized on the Buffer, no?
byte[] array = dst.array();
return readBytes(peer, position, array, dst.position(), dst.remaining());
}
public int read(ByteBuffer dst) throws IOException {
int count = read(dst, position);
if (count > 0) position += count;
return count;
}
public int write(ByteBuffer src, long position) throws IOException {
if (!src.hasArray()) throw new IOException("Cannot handle " + src.getClass());
byte[] array = src.array();
return writeBytes(peer, position, array, src.position(), src.remaining());
}
public int write(ByteBuffer src) throws IOException {
int count = write(src, position);
if (count > 0) position += count;
return count;
}
public long position() throws IOException {
return getFilePointer();
}
public FileChannel position(long position) throws IOException {
seek(position);
return this;
}
};
}
}