Java File to URL fileToURL(File file)

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

Description

Returns a URL corresponding to the specified File or null if the File cannot be converted into a URL.

License

Open Source License

Declaration


public static URL fileToURL(File file) 

Method Source Code

//package com.java2s;
/**//from www  . ja v a 2 s  .c  o  m
 * The utillib library.
 * More information is available at http://www.jinchess.com/.
 * Copyright (C) 2002 Alexander Maryanovsky.
 * All rights reserved.
 *
 * The utillib library is free software; you can redistribute
 * it and/or modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * The utillib library is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with utillib library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.io.File;

import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    /**
     * Returns a <code>URL</code> corresponding to the specified <code>File</code>
     * or <code>null</code> if the <code>File</code> cannot be converted into a
     * <code>URL</code>.
     * NOTE: This is copied from the JDK1.3 source, File.java
     */

    public static URL fileToURL(File file) {
        try {
            String path = file.getAbsolutePath();
            if (File.separatorChar != '/')
                path = path.replace(File.separatorChar, '/');
            if (!path.startsWith("/"))
                path = "/" + path;
            if (!path.endsWith("/") && file.isDirectory())
                path = path + "/";
            return new URL("file", "", path);
        } catch (MalformedURLException e) {
            return null;
        }
    }
}

Related

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