BufferedRAFInputStream.java 2.6 KB
/*
 * Decompiled with CFR 0_118.
 */
package com.day.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

public class BufferedRAFInputStream
extends InputStream {
    private final byte[] buffer = new byte[8192];
    private RandomAccessFile raf;
    private long bufferStart;
    private int bufferPos;
    private int bufferEnd;
    private byte[] one = new byte[1];

    public BufferedRAFInputStream(RandomAccessFile file) throws IOException {
        this.raf = file;
        this.bufferStart = this.raf.getFilePointer();
    }

    public int read() throws IOException {
        int r = this.read(this.one, 0, 1);
        return r >= 0 ? this.one[0] : -1;
    }

    public int read(byte[] b) throws IOException {
        return this.read(b, 0, b.length);
    }

    public int read(byte[] b, int off, int len) throws IOException {
        if (this.bufferEnd < 0) {
            return -1;
        }
        int total = 0;
        while (total < len && this.bufferEnd >= 0) {
            int toCopy = Math.min(this.bufferEnd - this.bufferPos, len - total);
            System.arraycopy(this.buffer, this.bufferPos, b, off, toCopy);
            this.bufferPos += toCopy;
            total += toCopy;
            off += toCopy;
            if (this.bufferPos != this.bufferEnd) continue;
            this.bufferStart = this.raf.getFilePointer();
            this.bufferEnd = this.raf.read(this.buffer);
            this.bufferPos = 0;
        }
        return total;
    }

    public long skip(long n) throws IOException {
        if (this.bufferEnd < 0) {
            return -1;
        }
        int len = this.bufferEnd - this.bufferPos;
        if (n < (long)len) {
            this.bufferPos = (int)((long)this.bufferPos + n);
            return n;
        }
        int sk = this.raf.skipBytes((int)(n - (long)len));
        this.bufferEnd = 0;
        this.bufferPos = 0;
        this.bufferStart = this.raf.getFilePointer();
        return sk + len;
    }

    public void seek(long n) throws IOException {
        this.bufferPos = (int)(n - this.bufferStart);
        if (this.bufferPos < 0 || this.bufferPos > this.bufferEnd) {
            this.bufferStart = n;
            this.bufferPos = 0;
            this.bufferEnd = 0;
            this.raf.seek(n);
        }
    }

    public long getFilePointer() throws IOException {
        return this.bufferStart + (long)this.bufferPos;
    }

    public int available() throws IOException {
        return (int)(this.raf.length() - (this.bufferStart + (long)this.bufferPos));
    }

    public void close() throws IOException {
        this.raf = null;
    }
}