Recipe 18.11 Converting a Filename to a URL


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


Use getResource( ) or File.toURL( ) .


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; u = c.getResource("");          System.out.println(u);      }  }

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


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 { u = new File("").toURL( );         System.out.println(u);     } }

Both programs print essentially the same result:

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

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

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: