[jdom-interest] SAXBuilder.fileToURL doesn't handle special characters
Ben Preece
ben.preece at qlogic.com
Fri Dec 19 09:44:08 PST 2003
We've been using JDOM for our application, and like it pretty well. Thanks for the hard work people have put into it. It shows.
We noticed that the method fileToURL() in SAXBuilder doesn't try to handle special characters. This causes the build(File) method to throw exceptions if the file name contains things like sharps ('#') or percents ('%'). The modified version below seems to handle it okay. Please feel free to use it if you want.
Again, thanks for all the work you've done.
-Ben Preece
public static URL fileToURL (File file)
throws MalformedURLException
{
StringBuffer buffer = new StringBuffer();
String path = file.getAbsolutePath();
// convert non-URL style file separators
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
// make sure it starts at root
if (!path.startsWith("/")) {
buffer.append('/');
}
// copy, converting URL special characters as we go
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c == ' ')
buffer.append ("%20");
else if (c == '#')
buffer.append ("%23");
else if (c == '%')
buffer.append ("%25");
else if (c == '&')
buffer.append ("%26");
else if (c == ';')
buffer.append ("%3B");
else if (c == '<')
buffer.append ("%3C");
else if (c == '=')
buffer.append ("%3D");
else if (c == '>')
buffer.append ("%3E");
else if (c == '?')
buffer.append ("%3F");
else if (c == '~')
buffer.append ("%7E");
else
buffer.append (c);
}
// make sure directories end with slash
if (!path.endsWith("/") && file.isDirectory()) {
buffer.append('/');
}
// return URL
return new URL("file", "", buffer.toString());
}
More information about the jdom-interest
mailing list