Java Resource Get getResourceAsFile(String name)

Here you can find the source of getResourceAsFile(String name)

Description

Returns a File pointing to a resource, given its name.

License

Open Source License

Parameter

Parameter Description
name Name of the resource.

Return

File pointing to the resource.

Declaration

public static File getResourceAsFile(String name) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.net.URL;

public class Main {
    /**//w  w w  .j a v a 2 s  .  co  m
     * Returns a File pointing to a resource, given its name.
     * 
     * @param name
     *          Name of the resource.
     * @return File pointing to the resource.
     */
    public static File getResourceAsFile(String name) {
        String resource = getResourceAsString(name);

        // Checks if the URL starts with vfs:/ and replace it with file:/
        if (resource.startsWith("vfs:/"))
            ;
        resource.replace("vfs:/", "file:/");

        return (resource == null) ? null : new File(resource);
    }

    /**
     * Returns the URL to a resource as String, given its name.
     * 
     * @param name
     *          Name of the resource.
     * @return String form of the resource's URL.
     */
    public static String getResourceAsString(String name) {
        URL resource = getResourceAsURL(name);
        return (resource == null) ? null : resource.getPath();
    }

    /**
     * Returns the URL to a resource, given its name.
     * 
     * @param name
     *          Name of the resource.
     * @return URL to the resource.
     */
    public static URL getResourceAsURL(String name) {
        return getContextClassLoader().getResource(name);
    }

    /**
     * Obtains the class loader of the current thread.
     * 
     * @return The class loader of the current thread.
     */
    private static ClassLoader getContextClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }
}

Related

  1. getResourceAsFile(Class clazz, String fn)
  2. getResourceAsFile(Class clazz, String name)
  3. getResourceAsFile(Class clazz, String rscName)
  4. getResourceAsFile(final Class clazz, final String name)
  5. getResourceAsFile(final String filename, final Class theClass)
  6. getResourceAsStream(Class aClass, String name)
  7. getResourceAsStream(final Class caller, final String resource)
  8. getResourceAsStream(String resourceLocation)
  9. getResourceAsString(String prefix, String resource)