W3C home > Mailing lists > Public > uri@w3.org > May 2005

Converting filenames to file: URIs

From: Graham Klyne <gk@ninebynine.org>
Date: Thu, 12 May 2005 13:40:16 +0100
Message-Id: <5.1.0.14.2.20050512131452.00b9b278@127.0.0.1>
To: <uri@w3.org>

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

This archive was generated by hypermail 2.3.1 : Tuesday, 6 January 2015 21:25:09 UTC