Converting filenames to file: URIs

I've recently been tinkering with a Java program that uses URIs, finding 
that it doesn't work on Windows because of its filename->URI conversion 
logic.  This has prompted me to map out a generic function to map a 
filename to a file: URI.

Examples:
Unix:
   Filename /foo/bar maps to file:///foo/bar
   i.e. prepend "file://"
Windows:
   Filename C:\foo\bar maps to file:///C:foo/bar
   i.e. prepend "file:///" and map \ to /.

This has prompted me to try and create a generic, operating-system 
independent function to turn (almost all) filename strings into 
corresponding file: URI string.  My first attempt is this, which attempts 
to cover Windows and Unix:

[[
     public static String uriFromFilename(
         String filename)
         {
         StringBuffer mapfilename = new StringBuffer( filename ) ;
         for ( int i = 0 ; i < mapfilename.length() ; i++ )
             {
             if ( mapfilename.charAt(i) == '\\' )
                 mapfilename.setCharAt(i, '/') ;
             }
         if (filename.charAt(0) == '/')
             {
             return "file://"+mapfilename.toString() ;
             }
         else
             {
             return "file:///"+mapfilename.toString() ;
             }
         }
]]

What's missing here?  How does this stand up on a Mac platform?

#g


------------
Graham Klyne
For email:
http://www.ninebynine.org/#Contact

Received on Thursday, 12 May 2005 13:16:05 UTC