Java URL Create convertToUrl(String[] paths)

Here you can find the source of convertToUrl(String[] paths)

Description

Convert string paths into URL class paths.

License

Apache License

Declaration

public static URL[] convertToUrl(String[] paths) 

Method Source Code


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

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

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

    /**//w  w w  .ja va  2 s.c  o m
     * Convert string paths into URL class paths.
     */
    public static URL[] convertToUrl(String[] paths) {
        ArrayList<URL> list = new ArrayList<URL>();
        for (int i = 0; i < paths.length; i++) {
            URL url = convertToUrl(paths[i]);
            if (url != null) {
                list.add(url);
            }
        }
        return list.toArray(new URL[list.size()]);
    }

    /**
     * Convert string path into URL class path.
     */
    public static URL convertToUrl(String path) {
        if (isEmpty(path)) {
            return null;
        }
        try {
            return new URL(PROTOCAL_PREFIX + convertUrlString(path));
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    private static boolean isEmpty(String s) {
        return s == null || s.trim().length() == 0;
    }

    /**
     * Convert a string path to be used in URL class path entry.
     */
    public static String convertUrlString(String classpath) {

        if (isEmpty(classpath)) {
            return "";
        }

        classpath = classpath.trim();
        if (classpath.length() < 2) {
            return "";
        }
        if (classpath.charAt(0) != '/' && classpath.charAt(1) == ':') {
            // add leading slash for windows platform
            // assuming drive letter path
            classpath = "/" + classpath;
        }
        if (!classpath.endsWith("/")) {
            File file = new File(classpath);
            if (file.exists() && file.isDirectory()) {
                classpath = classpath.concat("/");
            }
        }
        return classpath;
    }
}

Related

  1. constructURL(URL base, String url, boolean stripRef)
  2. constructURLQueryString(Map urlParameters)
  3. constructURLString(Map parameters)
  4. convertToURL(String host)
  5. convertToURL(String url)
  6. convertToURLs(String[] hosts)
  7. createURL(final String address)
  8. createURL(final String protocol, final String userInfo, final String host, final int port, final String path, final String query, final String ref)
  9. createUrl(final String spec)