001package org.unix4j.io;
002
003import java.io.InputStream;
004
005/**
006 * Input device reading a resource using
007 * {@link Class#getResourceAsStream(String)}.
008 */
009public class ResourceInput extends StreamInput {
010        /**
011         * Creates an input object opening the given {@code resource} using
012         * {@link Class#getResourceAsStream(String)} with {@code ResourceInput} ase
013         * base class.
014         * 
015         * @param resource
016         *            a path to the file on the classpath; if the file is in the
017         *            root directory, the filename should be prefixed with a forward
018         *            slash, e.g.: {@code "/test-file.txt"}; if the file is in a
019         *            package, then the package should be specified prefixed with a
020         *            forward slash, and with each dot "." replaced with a forward
021         *            slash. e.g.: {@code "/org/company/mypackage/test-file.txt"}
022         * @see Class#getResource(String)
023         * @see Class#getResourceAsStream(String)
024         */
025        public ResourceInput(String resource) {
026                super(openStream(ResourceInput.class, resource.startsWith("/") ? resource : "/" + resource));
027        }
028
029        /**
030         * Creates an input object opening the given {@code resource} using
031         * {@link Class#getResourceAsStream(String)} with the given base class.
032         *
033         * @param base
034         *                        the base class used to load the resource
035         * @param resource
036         *            a path to the file on the classpath; if the file is in the
037         *            root directory, the filename should be prefixed with a forward
038         *            slash, e.g.: {@code "/test-file.txt"}; if the file is in a
039         *            package, then the package should be specified prefixed with a
040         *            forward slash, and with each dot "." replaced with a forward
041         *            slash. e.g.: {@code "/org/company/mypackage/test-file.txt"}
042         * @see Class#getResource(String)
043         * @see Class#getResourceAsStream(String)
044         */
045        public ResourceInput(Class<?> base, String resource) {
046                super(openStream(base, resource));
047        }
048
049        private static InputStream openStream(Class<?> base, String resource) {
050                final InputStream stream = base.getResourceAsStream(resource);
051                if (stream != null) {
052                        return stream;
053                }
054                throw new IllegalArgumentException("resource not found: " + resource);
055        }
056}