Java Resource File getFile(String resource)

Here you can find the source of getFile(String resource)

Description

Multi protocol resource loader.

License

Apache License

Parameter

Parameter Description
resource a generic resource.

Return

a File pointing to the resource.

Declaration

public static File getFile(String resource) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.net.URL;

public class Main {
    /**// w  w  w .j  a  va  2 s .  c o  m
     * Multi protocol resource loader. Primary attempt is direct file, secondary is classpath resolved to File.
     *
     * @param resource a generic resource.
     * @return a File pointing to the resource.
     */
    public static File getFile(String resource) throws IOException {
        File directFile = new File(resource);
        if (directFile.exists()) {
            return directFile;
        }
        URL classLoader = Thread.currentThread().getContextClassLoader().getResource(resource);
        if (classLoader == null) {
            throw new FileNotFoundException("Unable to locate '" + resource + "' as direct File or on classpath");
        }
        String fromURL = classLoader.getFile();
        if (fromURL == null || fromURL.isEmpty()) {
            throw new FileNotFoundException("Unable to convert URL '" + fromURL + "' to File");
        }
        return new File(fromURL);
    }
}

Related

  1. getDefaultWebXmlResourceLocation()
  2. getEntriesFromResourceBundle(String rbName, Map map)
  3. getFile(Class clazz, String resource)
  4. getFile(Class resourceClass, String fileName)
  5. getFile(Class cls, String resource)
  6. getFile(String resourceOrFile, Class cls, boolean deleteTmpOnExit)
  7. getFileByResources(String fileName, Class clazz)
  8. getFileFromRelativeResource(final Class type, final String relativeResourceName)
  9. getFileFromSystemResources(String fileName)