Java Path to URL getURL(String path, URL context)

Here you can find the source of getURL(String path, URL context)

Description

Given an address and the context (referrer URL/current directory), try to create a URL object.

License

Open Source License

Parameter

Parameter Description
path a parameter
context a parameter

Declaration

public static URL getURL(String path, URL context) 

Method Source Code


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

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

public class Main {
    /**/*from  w ww .  j  av  a2s.  co  m*/
     * Given an address and the context (referrer URL/current directory), try to
     * create a URL object.
     * @param path
     * @param context
     * @return
     */
    public static URL getURL(String path, URL context) {
        URL result;
        // If there's no context, first try to parse as a local file.
        if (context == null) {
            result = resolveFile(new File(path));
            if (result != null)
                return result;
        }

        // Try to use standard URL handling to obtain the new URL.
        try {
            result = new URL(context, path);
        } catch (MalformedURLException ex) {
            return null;
        }

        // If we've found a file, try to resolve it in case it's a directory.
        if (result.getProtocol().equals("file")) {
            try {
                result = resolveFile(new File(result.toURI().getPath()));
            } catch (Exception e) {
                result = null;
            }
        }

        return result;
    }

    private static URL resolveFile(File file) {
        try {
            if (file.isDirectory())
                file = getIndexFile(file);
            else if (!file.exists())
                file = null;

            if (file != null) {
                return file.toURI().toURL();
            } else
                return null;
        } catch (Exception e) {
            return null;
        }
    }

    private static File getIndexFile(File directory) {
        // Use FilenameFilter to select index.htm and index.html files.
        String[] indexFiles = directory.list(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.equalsIgnoreCase("index.html") || name.equalsIgnoreCase("index.htm");
            }
        });
        // Return the first one we find, else null.
        if (indexFiles.length > 0)
            return new File(indexFiles[0]);
        return null;
    }
}

Related

  1. getURL(String host, int port, String path, boolean isHTTPS)
  2. getUrl(String inPath)
  3. getUrl(String ip, String port, String servicePath, String serviceName, String... args)
  4. getURL(String path)
  5. getURL(String path)
  6. getUrl(String pluginId, String relativePath)
  7. getURL(String schema, String host, String path)
  8. getUrl(URL base, String path)
  9. getUrlForLocalPath(String path)