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)}. 013 * 014 * @param resource 015 * a path to the file on the classpath; if the file is in the 016 * root directory, the filename should be prefixed with a forward 017 * slash, e.g.: {@code "/test-file.txt"}; if the file is in a 018 * package, then the package should be specified prefixed with a 019 * forward slash, and with each dot "." replaced with a forward 020 * slash. e.g.: {@code "/org/company/mypackage/test-file.txt"} 021 * @see Class#getResource(String) 022 * @see Class#getResourceAsStream(String) 023 */ 024 public ResourceInput(String resource) { 025 super(openStream(resource)); 026 } 027 028 private static InputStream openStream(String resource) { 029 final InputStream stream = ResourceInput.class.getResourceAsStream(resource); 030 if (stream != null) { 031 return stream; 032 } 033 throw new IllegalArgumentException("resource not found: " + resource); 034 } 035}