views:

279

answers:

2

First I'll provide a tiny code snippet here:

String path = "".equals(url.getPath()) ? "/" : url.getPath();
java.io.File f = new java.io.File(path);

if (!f.exists()) {
    this.code = 404;  // http Not Found
    return;
}

Here, the URL's type is java.net.URL,and its value has this format:

file:///directory1/directory2.../filename

the above code works 90% of the time when it's processing general URLs, But it fails when the file name has special characters in it. For example:

/tmp/Marissafolli/Receptionist/Administrative Assistant/Marissa's Resume.txt.txt

URLs like this will report a "404" code, even if they exist. The following version will work for those special cases:

java.io.File f = new java.io.File(url.toURI());

But url.toURI() is only in j2SE 1.5.0. So I need to use the first version. How can I make it work?

+2  A: 

It's not a bug, it's the fact that it's not a valid URL.

You obviously need to escape those blanks into %20, for starters. I don't know what you do with the apostrophe. This blog suggests that it should become a %27. Try it and see.

Or just try java.net.URLEncoder to see what it gives you.

duffymo
I don't believe you can use URLEncoder, as it will encode *everything* including the "://" characters. Java itself does not have a class to do the necessary encoding.
Eddie
You might be right, Eddie. I didn't try it myself. I was just rooting around for something in the API that might help. Perhaps that wasn't a good idea.
duffymo
A: 

Why not construct a URI first and then call the toURL() method. More info here.

[UPDATE] Or even better, why not use the URI directly in the constructor of the File, since the URI class takes care of the encoding for you.

Mihai Fonoage