Pastebin / FirstByteReader.java

Ethicist 22 января 2018
import java.io.IOException;
import java.io.InputStream;

/**
 * Read fixed number of bytes from a file
 * @author Ethicist
 */
public class FirstByteReader {

    private String path;
    InputStream stream = null;

    public byte[] readBytes(String path, int size, boolean allowless) {
        byte temp[] = new byte[size];
        int length = 0;
        this.path = path;
        stream = this.getClass().getResourceAsStream(path);
        try {
            int read = stream.read();
            while (length < size) {
                read = stream.read(temp, length, size - length);
                if (read == -1) {
                    if (allowless) {
                        byte buffer[] = new byte[length];
                        System.arraycopy(temp, 0, buffer, 0, length);
                        // return a smaller array, so the caller
                        // can tell how much they really got
                        return buffer;
                    } else { // something goes wrong
                        if (length > 0) {
                            echo("EOF while reading data");
                        } else {
                            throw new IOException();
                        }
                    }
                }
                length += read;
            }
        } catch (IOException i) {
            showExceptionMessage(i, "FileInputReader: readBytes IOException: " );
        }
        echo("result is: " + new String(temp));
        return temp;
    }

    protected void echo(String s) {
        System.out.println(s);
    }

    public static FirstByteReader getInstance() {
        return new FirstByteReader();
    }

    private void showExceptionMessage(Exception e, String message) {
        System.err.println("O b o s r a l s y a !");
        String err = e.getMessage() + "\n" + e.toString();
        System.out.println(message + err + "\n");
        e.printStackTrace();
    }
}

Смотрите также: