file URLs again

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


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;
            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

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

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

More information about the Xml-dev mailing list