Paul Paul - 1 year ago 111
Java Question

Convert between URL and windows filename (Java)?

Is there a standard/good way of converting between urls and windows filenames, in Java?

I am trying to download files, but I want the windows filename to be convertible back to the original filename. Note that the query portion of the url is vital, as I will be downloading different pages that differ only in query.

My current hacky solution is to replace illegal characters (such as '?') with a specific string (such as 'QQ'), but this makes conversion back to url less transparent. Is there a better way?

Answer Source

You could do worse than use URLEncoder to encode the URL:

String url = "";
String filename = URLEncoder.encode(url, "UTF-8");
File file = new File(filename);

The filename becomes the legal win32 name:


This is a reversible operation:

String original = URLDecoder.decode(filename, "UTF-8");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download