Recipe 18.11 Converting a Filename to a URL


Problem

You require a URL, but you have a local file.

Solution

Use getResource( ) or File.toURL( ) .

Discussion

Many operations require a URL, but it would be easier to refer to a file on the local filesystem or disk. For these, the convenience method getResource( ) in the class java.lang.Class can be used. This takes a filename and returns a URL:

public class GetResource {      public static void main(String[] argv) {          Class c = GetResource.class;          java.net.URL u = c.getResource("GetResource.java");          System.out.println(u);      }  }

When I ran this code on my Windows system, it printed:

file:/C:/javasrc/netweb/GetResource.java

JDK 1.2 also introduced a toURL( ) method into the File class (Recipe 11.1). Unlike getResource( ), this method can throw a MalformedURLException . This makes sense, since a File object can be constructed with arbitrary nonsense in the filename. So the previous code can be rewritten as:

public class FileToURL {     public static void main(String[] argv) throws MalformedURLException {         java.net.URL u = new File("GetResource.java").toURL( );         System.out.println(u);     } }

Both programs print essentially the same result:

> java FileToURL file:/usr/home/ian/javasrc/netweb/GetResource.java > java GetResource file:/usr/home/ian/javasrc/netweb/GetResource.java



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net