Java Path File Read nio getResourceAsStream(String resourcePath, ClassLoader classLoader, Class clazz, String resourceDesc, Consumer logger)

Here you can find the source of getResourceAsStream(String resourcePath, ClassLoader classLoader, Class clazz, String resourceDesc, Consumer logger)

Description

Get the InputStream input stream to the resource given by the supplied path.

License

Apache License

Parameter

Parameter Description
resourcePath the logical path to the classpath, file, or URL resource
classLoader the classloader that should be used to load the resource as a stream; may be null
clazz the class that should be used to load the resource as a stream; may be null
resourceDesc the description of the resource to be used in messages sent to logger ; may be null
logger a function that is to be called with log messages describing what is being tried; may be null

Exception

Parameter Description
IllegalArgumentException if the resource path is null or empty

Return

an input stream to the resource; or null if the resource could not be found

Declaration

public static InputStream getResourceAsStream(String resourcePath, ClassLoader classLoader, Class<?> clazz,
        String resourceDesc, Consumer<String> logger) 

Method Source Code


//package com.java2s;
/*//  w ww.j a v  a 2 s  .c  o m
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 * 
 * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
 */

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;
import java.nio.file.FileSystems;

import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.util.function.Consumer;

public class Main {
    /**
     * Get the {@link InputStream input stream} to the resource given by the supplied path. This method performs these operations
     * in order, returning as soon as a file is found:
     * <ol>
     * <li>look for a file on the file system at the given absolute path; otherwise</li>
     * <li>look for a file on the file system at the given path relative to the JVM process; otherwise</li>
     * <li>if a {@code classloader} is supplied, use it to load the file on the classpath at the given path; otherwise</li>
     * <li>if a {@code clazz} is supplied, use it to load the file on its classpath at the given path; otherwise</li>
     * <li>try to convert the path to a URL and obtain the referenced resource</li>
     * </ol>
     * If all of these fail, this method returns null.
     * 
     * @param resourcePath the logical path to the classpath, file, or URL resource
     * @param classLoader the classloader that should be used to load the resource as a stream; may be null
     * @param clazz the class that should be used to load the resource as a stream; may be null
     * @param resourceDesc the description of the resource to be used in messages sent to {@code logger}; may be null
     * @param logger a function that is to be called with log messages describing what is being tried; may be null
     * @return an input stream to the resource; or null if the resource could not be found
     * @throws IllegalArgumentException if the resource path is null or empty
     */
    public static InputStream getResourceAsStream(String resourcePath, ClassLoader classLoader, Class<?> clazz,
            String resourceDesc, Consumer<String> logger) {
        if (resourcePath == null)
            throw new IllegalArgumentException("resourcePath may not be null");
        if (resourceDesc == null && logger != null)
            resourceDesc = resourcePath;
        InputStream result = null;
        if (result == null) {
            try {
                // Try absolute path ...
                Path filePath = FileSystems.getDefault().getPath(resourcePath).toAbsolutePath();
                File f = filePath.toFile();
                if (f.exists() && f.isFile() && f.canRead()) {
                    result = new BufferedInputStream(new FileInputStream(f));
                }
                logMessage(result, logger, resourceDesc, "on filesystem at " + filePath);
            } catch (InvalidPathException e) {
                // just continue ...
            } catch (FileNotFoundException e) {
                // just continue ...
            }
        }
        if (result == null) {
            try {
                // Try relative to current working directory ...
                Path current = FileSystems.getDefault().getPath(".").toAbsolutePath();
                Path absolute = current.resolve(Paths.get(resourcePath)).toAbsolutePath();
                File f = absolute.toFile();
                if (f.exists() && f.isFile() && f.canRead()) {
                    result = new BufferedInputStream(new FileInputStream(f));
                }
                logMessage(result, logger, resourceDesc,
                        "on filesystem relative to '" + current + "' at '" + absolute + "'");
            } catch (InvalidPathException e) {
                // just continue ...
            } catch (FileNotFoundException e) {
                // just continue ...
            }
        }
        if (result == null && classLoader != null) {
            // Try using the class loader ...
            result = classLoader.getResourceAsStream(resourcePath);
            logMessage(result, logger, resourceDesc, "on classpath");
        }
        if (result == null && clazz != null) {
            // Not yet found, so try the class ...
            result = clazz.getResourceAsStream(resourcePath);
            if (result == null) {
                // Not yet found, so try the class's class loader ...
                result = clazz.getClassLoader().getResourceAsStream(resourcePath);
            }
            logMessage(result, logger, resourceDesc, "on classpath");
        }
        if (result == null) {
            // Still not found, so try to construct a URL out of it ...
            try {
                URL url = new URL(resourcePath);
                result = url.openStream();
                logMessage(result, logger, resourceDesc, "at URL " + url.toExternalForm());
            } catch (MalformedURLException e) {
                // just continue ...
            } catch (IOException err) {
                // just continue ...
            }
        }
        // May be null ...
        return result;
    }

    private static void logMessage(InputStream stream, Consumer<String> logger, String resourceDesc, String msg) {
        if (stream != null && logger != null) {
            logger.accept("Found " + resourceDesc + " " + msg);
        }
    }
}

Related

  1. breadcrumbPath(String urlPrefix, String path, char sep)
  2. checkReadableDirectory(final Path directory)
  3. getReaderForFile(final Path file)
  4. getTestClassPathURLClassLoader(ClassLoader parent)
  5. load(Path p, PrintStream errorStream, String propertyInfo)
  6. loadFile(final Path filePath)
  7. loadFile(final Path p)