OO-Snippets: Create UNO compatible URL

Commons

KeywordsURL, UNO, File, file:///
LanguageJava
ApplicationOffice
AuthorsTobias Krais
Supported Versions2.0.x  1.1.x  
Supported OSAll  
QuestionHow to create a URL that is usable by UNO from a normal file location

Normal file locations are e.g.:

for Linux/UNIX: "/tmp/myDocument.odt"

for Windows: "C:\myFolder\myDocument"

But UNO needs this (e.g. for Linux) "file:///tmp/myDocument.odt".

The code below explains how to solve this in Java

Answer

Code-Snippet-Listing (snippet-source)

    /**
     * Creating a correct File URL that OpenOffice can handle. This is
     * necessary to be platform independent.
     * 
     * @param filelocation
     * @return
     */
    public String createUNOFileURL(String filelocation)
    {
        java.io.File newfile = new java.io.File(filelocation);
        java.net.URL before = null;
        try
        {
            before = newfile.toURL();
        }
        catch (MalformedURLException e) {
            System.out.println(e);
        }
        // Create a URL, which can be used by UNO
        String myUNOFileURL =  com.sun.star.uri.ExternalUriReferenceTranslator
          .create(xRemoteContext).translateToInternal(before.toExternalForm());

        if (myUNOFileURL.length() == 0 && filelocation.length() > 0)
        {
            System.out.println("File URL conversion faild. Filelocation " +
                    "contains illegal characters: " + filelocation);
        }
        return myUNOFileURL;
    }

Changelog

DateUserModification
2006-03-27tobiaskraisInitial version

and