Java Path to URL toUrl(final String path)

Here you can find the source of toUrl(final String path)

Description

Convert a local file path to a URL

License

Open Source License

Parameter

Parameter Description
path the local file path to parse into a URL

Exception

Parameter Description
IOException if there is an error creating the URL

Return

the URL corresponding to the specified file/folder path

Declaration

public static final URL toUrl(final String path) throws IOException 

Method Source Code

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

import java.io.File;

import java.io.IOException;

import java.net.URL;

public class Main {
    private static final String fileProtocolPrefix = "file:///";

    /** Convert a local file path to a {@link URL}
     * @param path the local file path to parse into a URL
     * @return the URL corresponding to the specified file/folder path
     * @throws IOException if there is an error creating the URL
     *//*from  w w  w .  ja va 2 s .co m*/
    public static final URL toUrl(final String path) throws IOException {
        URL url = null;
        if (path.startsWith(fileProtocolPrefix)) {
            url = new URL(path);
        } else {
            // Convert the path to a URL
            try {
                url = new URL(path);
            } catch (Exception e) {
                // If the path cannot be directly converted to a URL
                // convert it to a file first and then convert it to a URL
                File file = new File(path).getCanonicalFile();
                url = file.toURI().toURL();
            }
        }
        return url;
    }
}

Related

  1. pathToUrl(String path)
  2. pathToURL(String path)
  3. pathToURLs(String path)
  4. pathToURLs(String path)
  5. toTargetURL(String path)
  6. toURL(String path)
  7. toURL(String pathPrefix, String jar)
  8. toURLs(String... paths)
  9. toURLs(String[] classPath)