2008年3月14日 星期五

快速讀檔

主程式

FileChannel fch = new RandomAccessFile(path, "r").getChannel();

ByteBuffer roBuf = fch.map(FileChannel.MapMode.READ_ONLY, 0, (int) fch.size());

BufferedReader br = new BufferedReader(new InputStreamReader(newInputStream(roBuf)));


while ((thisLine = br.readLine())!=null) {

}

副程式

public static InputStream newInputStream(final ByteBuffer buf) {
return new InputStream() {
public synchronized int read() throws IOException {
if (!buf.hasRemaining()) {
return -1;
}
return buf.get();
}

public synchronized int read(byte[] bytes, int off, int len) throws IOException {
// Read only what's left
len = Math.min(len, buf.remaining());
buf.get(bytes, off, len);
return len;
}
};
}

沒有留言: