name.martingeisse.esdk.util.ImmutableByteArray.java Source code

Java tutorial

Introduction

Here is the source code for name.martingeisse.esdk.util.ImmutableByteArray.java

Source

/**
 * Copyright (c) 2016 Martin Geisse
 *
 * This file is distributed under the terms of the MIT license.
 */

package name.martingeisse.esdk.util;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;

/**
 * Wraps a byte array but only allows immutable access.
 */
public final class ImmutableByteArray {

    private final byte[] data;

    /**
     * Creates an instance by copying an existing data array.
     *
     * @param data the data array to copy
     */
    public ImmutableByteArray(final byte[] data) {
        this(data, true);
    }

    /**
     * Creates an instance by loading a file.
     * 
     * @param file the file to load
     * @throws IOException on I/O errors
     */
    public ImmutableByteArray(final File file) throws IOException {
        this(FileUtils.readFileToByteArray(file), false);
    }

    /**
     * Internal constructor.
     */
    private ImmutableByteArray(final byte[] data, final boolean copy) {
        this.data = copy ? Arrays.copyOf(data, data.length) : data;
    }

    /**
     * Getter method for the data. This returns a copy of the internal data array.
     *
     * @return the data
     */
    public byte[] getData() {
        return Arrays.copyOf(data, data.length);
    }

    /**
     * Gets the length of this array.
     *
     * @return the length of this array
     */
    public int length() {
        return data.length;
    }

    /**
     * Gets an element of this array.
     *
     * @param index the element index
     * @return the element value
     */
    public byte get(final int index) {
        return data[index];
    }

}