Java Path File Read nio loadProperties(Supplier classLoader, String classpathResource)

Here you can find the source of loadProperties(Supplier classLoader, String classpathResource)

Description

Atomically load the properties file at the given location within the designated class loader.

License

Apache License

Parameter

Parameter Description
classLoader the supplier for the class loader; may not be null or return null
classpathResource the path to the resource file; may not be null

Exception

Parameter Description
IllegalStateException if the file could not be found or read

Return

the properties object; never null, but possibly empty

Declaration

public static Properties loadProperties(Supplier<ClassLoader> classLoader, String classpathResource) 

Method Source Code


//package com.java2s;
/*/*from w ww  . j av  a2s.co 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.Properties;

import java.util.function.Consumer;
import java.util.function.Supplier;

public class Main {
    /**
     * Atomically load the properties file at the given location within the designated class loader.
     * @param classLoader the supplier for the class loader; may not be null or return null
     * @param classpathResource the path to the resource file; may not be null
     * @return the properties object; never null, but possibly empty
     * @throws IllegalStateException if the file could not be found or read
     */
    public static Properties loadProperties(Supplier<ClassLoader> classLoader, String classpathResource) {
        // This is idempotent, so we don't need to lock ...
        try (InputStream stream = classLoader.get().getResourceAsStream(classpathResource)) {
            Properties props = new Properties();
            props.load(stream);
            return props;
        } catch (IOException e) {
            throw new IllegalStateException("Unable to find or read the '" + classpathResource + "' file using the "
                    + classLoader + " class loader", e);
        }
    }

    /**
     * Atomically load the properties file at the given location within the designated class loader.
     * @param classLoader the class loader; may not be null
     * @param classpathResource the path to the resource file; may not be null
     * @return the properties object; never null, but possibly empty
     * @throws IllegalStateException if the file could not be found or read
     */
    public static Properties loadProperties(ClassLoader classLoader, String classpathResource) {
        return loadProperties(() -> classLoader, classpathResource);
    }

    /**
     * Atomically load the properties file at the given location within the designated class' class loader.
     * @param clazz the class whose class loader is to be used; may not be null
     * @param classpathResource the path to the resource file; may not be null
     * @return the properties object; never null, but possibly empty
     * @throws IllegalStateException if the file could not be found or read
     */
    public static Properties loadProperties(Class<?> clazz, String classpathResource) {
        return loadProperties(clazz::getClassLoader, classpathResource);
    }

    /**
     * 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. loadFile(Path file)
  2. loadFile(String path)
  3. loadFromFile(Path path)
  4. loadJSON(Path path)
  5. loadProperties(Path filePath)
  6. loadStrings(Path thePath)
  7. loadStringsFromFile(String pathToFile)
  8. loadTestPackets(final Path path)
  9. loadTitles(Path rootDir, Set container)