Java URL Relative getRelativeURLAsStream(Class clazz, String fileName)

Here you can find the source of getRelativeURLAsStream(Class clazz, String fileName)

Description

get the input stream of a file relative to (in the same directory as) the specified .class file
can also be used if the .class file resides inside a .jar file

License

Open Source License

Parameter

Parameter Description
clazz The class next to the file
fileName The name of the file

Return

The input stream of the file, can be null

Declaration

public static InputStream getRelativeURLAsStream(Class<?> clazz,
        String fileName) 

Method Source Code

//package com.java2s;

import java.io.InputStream;

public class Main {
    /**/* ww  w.j  ava 2s .  c  o  m*/
     * get the input stream of a file relative to (in the same directory as) the specified .class
     * file<br>
     * can also be used if the .class file resides inside a .jar file
     * 
     * @param clazz
     *            The class next to the file
     * @param fileName
     *            The name of the file
     * 
     * @return The input stream of the file, can be null
     */
    public static InputStream getRelativeURLAsStream(Class<?> clazz,
            String fileName) {
        String filePath = getRelativePackagePath(clazz) + "/" + fileName;
        return Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(filePath);
    }

    /**
     * build the package path for the class loader<br>
     * the class loader should be able to load a file appended to this path, if it is in the same
     * directory.
     * 
     * @param clazz
     *            The class
     * 
     * @return The package path
     */
    private static String getRelativePackagePath(Class<?> clazz) {
        String className = clazz.getName();
        String packageName = className.substring(0,
                className.lastIndexOf("."));
        return packageName.replace('.', '/');
    }
}

Related

  1. getRelativeNameOrURL(File baseDir, File file)
  2. getRelativeURI(File fromFile, File toFile)
  3. getRelativeURL(File base, File file)
  4. getRelativeUrl(File basePath, File targetPath)