Java File to URL fileToURL(File f)

Here you can find the source of fileToURL(File f)

Description

This method is added because the default conversion using file.toURL() turns out to be rather slow, as it tries to figure out if the file is actually a directory.

License

Open Source License

Declaration

public static URL fileToURL(File f) throws IOException 

Method Source Code


//package com.java2s;
/* Aalto XML processor/*from   w w w . j a v a  2s .c o m*/
 *
 * Copyright (c) 2006- Tatu Saloranta, tatu.saloranta@iki.fi
 *
 * Licensed under the License specified in the file LICENSE which is
 * included with the source code.
 * You may not use this file except in compliance with the License.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    /**
     * This method is added because the default conversion using
     * <code>file.toURL()</code> turns out to be rather slow, as
     * it tries to figure out if the file is actually a directory.
     * Now, for our use cases this is irrelevant, so we can optimize
     * out that expensive part.
     */
    public static URL fileToURL(File f) throws IOException {
        /* Based on earlier experiences, looked like using
         * File.toURL() is rather expensive (at least on jdk1.4/1.5),
         * so let's just use a faster replacement
         */
        String absPath = f.getAbsolutePath();
        // Need to convert colons/backslashes to regular slashes?
        {
            char sep = File.separatorChar;
            if (sep != '/') {
                absPath = absPath.replace(sep, '/');
            }
        }
        if (absPath.length() > 0 && absPath.charAt(0) != '/') {
            absPath = "/" + absPath;
        }
        return new URL("file", "", absPath);
    }
}

Related

  1. FileToURL(File file)
  2. fileToURL(File file)
  3. fileToUrl(File file)
  4. fileToURL(File file)