package com.xypower.mpapp.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomReader {

    protected String fileName;

    protected RandomAccessFile seeker;

    /** Constructor: save filename, construct RandomAccessFile */
    public RandomReader(String fname, long offset) {
        fileName = fname;
        try {
            seeker = new RandomAccessFile(fname, "r");
            if (seeker != null) {
                seeker.seek(offset);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void finalize() {
        if (seeker != null) {
            try {
                seeker.close();
            } catch (Exception e) {
            }
        }
    }

    public void close() {
        if (seeker != null) {
            try {
                seeker.close();
            } catch (Exception e) {
            }
        }
    }

    /** Read the message at the given offset */
    public String readLine() {

        String line = null;
        try {
            if (seeker != null) {
                line = seeker.readLine();
            }
        } catch (Exception e) {

        }
        return line;
    }

    public int read(byte[] bytes) {
        int bytesRead = 0;
        try {
            if (seeker != null) {
                bytesRead = seeker.read(bytes);
            }
        } catch (Exception e) {
        }
        return bytesRead;
    }

    public long getOffset() {
        long offset = 0;
        try {
            offset = seeker.getChannel().position();
        } catch (Exception e) {

        }
        return offset;
    }

}
