Example 6-5: Helper class to handle string-based URL's intelligently

import java.io.*;
import java.net.*;
public class URLUtils {
   // Create a new URL from a string
   static URL newURL(String filename) throws MalformedURLException
   {
      URL url = null;
      try {
         // First try to see if filename is *already* a valid URL
         url = new URL(filename);
      }
      // If not, then assume it's a "naked" filename and make a URL
      catch (MalformedURLException ex) {
        // Get the absolute path of the file
        String path = (new File(filename)).getAbsolutePath();
        // If directory separator character is not a forward slash, make it so.
        if (File.separatorChar != '/') {
          path = path.replace(File.separatorChar,'/');
        }
        // Add a leading slash if path doesn't start with one (e.g. E:/foo/bar)
        if (!path.startsWith("/")) {
          path = "/"+path;
        }
        // Construct the file URL
        url = new URL("file://" + path);
     }
     return url;
   }
}