file URLs again

Don Park donpark at quake.net
Sat Feb 7 22:10:06 GMT 1998


Tim,

Try this:

public URL createFileURL (String fileName) {
    File file = new File(fileName);
    try {
        String path = file.getAbsolutePath();
        char sep = File.separatorChar;
        if (sep != '/')
            path = path.replace(sep, '/');
        if (path.charAt(0) == '/')
            path = "file://" + path;
        else
            path = "file:///" + path;
        return new URL(path);
    }
    catch (MalformedURLException e) {
        return null;
    }
}

I wish File.getCanonicalPath() could have been used instead of
getAbsolutePath() but it throws exception if the file does not exist.  If
that is the behavior you want, replace getAbsolutePath() with
getCanonicalPath().

I have used File.separatorChar instead of File.separator or even
getProperty("file.separator") because I don't know of any system that has
multicharacter separators.  It will be a lot more messy if you want to
handle that case as well.

Hope this helps,

Don Park
http://www.quake.net/~donpark/index.html



xml-dev: A list for W3C XML Developers. To post, mailto:xml-dev at ic.ac.uk
Archived as: http://www.lists.ic.ac.uk/hypermail/xml-dev/
To (un)subscribe, mailto:majordomo at ic.ac.uk the following message;
(un)subscribe xml-dev
To subscribe to the digests, mailto:majordomo at ic.ac.uk the following message;
subscribe xml-dev-digest
List coordinator, Henry Rzepa (mailto:rzepa at ic.ac.uk)




More information about the Xml-dev mailing list