Java Resource Path Get getAbsolutePathFromResource(Class reference, String resource)

Here you can find the source of getAbsolutePathFromResource(Class reference, String resource)

Description

Returns the absolute path of the resource.

License

Open Source License

Parameter

Parameter Description
urlResource a parameter

Declaration

public static String getAbsolutePathFromResource(Class reference, String resource) 

Method Source Code


//package com.java2s;
import java.net.URL;
import java.net.URLDecoder;

public class Main {
    /**/*from  w  ww .j  ava 2s .  c o  m*/
     * Returns the absolute path of the resource. All special characters like
     * spaces etc. are decoded properly.
     * 
     * @param class
     * @param urlResource
     * @return
     */
    public static String getAbsolutePathFromResource(String resource) {
        return getAbsolutePathFromResource(Object.class, resource);
    }

    /**
     * Returns the absolute path of the resource. All special characters like
     * spaces etc. are decoded properly.
     * 
     * @param urlResource
     * @return
     */
    public static String getAbsolutePathFromResource(Class reference, String resource) {
        URL urlResource = reference.getResource(resource);
        if (urlResource == null)
            return null;

        //    return URI.create(urlResource.toString()).getPath();
        //    problem: URI can't parse spaces in URL at all.

        String urlString = URLDecoder.decode(urlResource.toString());

        if (urlString.startsWith("jar:"))
            urlString = urlString.substring("jar:".length());
        if (urlString.startsWith("file:"))
            urlString = urlString.substring("file:".length());

        //linux: /path/dir
        //windows: /C:/path/dir , also weg mit lead /
        if (urlString.indexOf(':') == 2)
            urlString = urlString.substring(1);

        //other ideas?

        return urlString;
    }
}

Related

  1. classToResource(String className)
  2. deserialize(Class parentOfResource, String resourcePath, Class targetClass)
  3. existsResource(String pathName)
  4. getAbsoluteResource(String path)
  5. getAlternateResourceFile(final String resourcePath)
  6. getBasePath(Class clazz, String resource)
  7. getChildResources(String path)