001package org.unix4j.util;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.IOException;
006import java.io.InputStream;
007
008/**
009 * Class with static utility methods to load package or file resources.
010 */
011public class ResourceUtil {
012
013        /**
014         * Returns the specified resource as input stream. Uses
015         * {@link Class#getResourceAsStream(String)} falling back to {@link File} if
016         * the resource is not found. If neither method succeeds, an exception is
017         * thrown.
018         * 
019         * @param name
020         *            the resource name, a file name or a package relative resource
021         * 
022         * @return the resource as input stream, never null
023         * @throws IllegalArgumentException
024         *             if the resource cannot be found or read
025         */
026        public static InputStream getResource(Class<?> base, String name) {
027                final InputStream in = base.getResourceAsStream(name);
028                if (in != null) {
029                        return in;
030                }
031                try {
032                        return new FileInputStream(name);
033                } catch (IOException e) {
034                        throw new IllegalArgumentException("resource '" + name + "' not found");
035                }
036        }
037
038        // no instances
039        private ResourceUtil() {
040                super();
041        }
042}