Re: file URLs again

Don Park (donpark@quake.net)
Sat, 7 Feb 1998 14:04:33 -0800


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