Java examples for File Path IO:File Stream
Returns the input stream for the resource with the specified absolute name.
/*// w ww. j a v a 2 s.c o m * Copyright (c) 2015-2016 QuartzDesk.com. * Licensed under the MIT license (https://opensource.org/licenses/MIT). */ //package com.java2s; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; public class Main { public static void main(String[] argv) throws Exception { String absoluteName = "java2s.com"; System.out.println(getResourceAsStream(absoluteName)); } /** * Returns the input stream for the resource with the specified absolute name. * The resource is loaded through the current thread's context class loader. * * @param absoluteName a resource name. * @return the resource input stream. * @throws IOException if the resource was not found. */ public static InputStream getResourceAsStream(String absoluteName) throws IOException { String resourceName = absoluteName.startsWith("/") ? absoluteName .substring(1) : absoluteName; InputStream ins = Thread.currentThread().getContextClassLoader() .getResourceAsStream(resourceName); if (ins == null) throw new IOException("Cannot find resource: " + absoluteName); return new BufferedInputStream(ins); } /** * Returns the input stream for the resource with the specified relative name. * The name is treated as relative and the package name of the specified * class is prepended to that name to make the name absolute. The resource * is loaded through the current thread's context class loader. * * @param relativeName a resource name (relative, or absolute). * @param clazz a class used to make the resource name absolute and load the resource. * @return the resource input stream. * @throws IOException if the resource was not found. */ public static InputStream getResourceAsStream(String relativeName, Class<?> clazz) throws IOException { String newName = getAbsoluteResourceName(relativeName, clazz); return getResourceAsStream(newName); } /** * Simply prepends the package name of the specified class to the * specified name and replaces all '.' with '/'. * * @param name a resource name. * @param clazz a class to be used to resolve the name if it * is a relative name. * @return the absolute resource name. */ public static String getAbsoluteResourceName(String name, Class<?> clazz) { StringBuilder absName = new StringBuilder(clazz.getPackage() .getName().replace('.', '/')); absName.append('/'); absName.append(name); return absName.toString(); } }