I was working on a project, which required the ability to export the contents of the table as a Microsoft Excel file. After saving the file, the file had to be open immediately by Microsoft Excel. However this is multi-platform application and needed to support at least Windows, Mac and Linux. What if the user didn’t have Microsoft Excel installed, but they did have another program capable of editing/viewing Excel files? Users may have installed alternatives such as Open Office, Libre Office, and Microsoft Office for Mac. How can a Java Swing program invoke an unknown native program without having to program to every native executable? After searching the web, there was an elegant solution.
Each operating system such as Windows, Mac and Linux has an executable that can be called and depending on the parameters it will invoke the default program associated with the content type. If you pass it a URL, it will invoke the default web browser and navigate to the URL. If you pass it a PDF, it might invoke Adobe Reader or any other program capable of viewing PDFs. Likewise for other file types such as Microsoft Word documents or Excel spreadsheets.
To keep the complexity hidden from you, I wrote a simple Launcher class that will translate to the platform-specific commands.
To open a URL:
Launcher.open("http://www.java.com");
To open a Excel file:
Launcher.open("file:///home/jim/Downloads/forecasts.xls");
To open a pdf file:
Launcher.open("file:///home/jim/Downloads/forecasts.pdf");
Download my utility class below. (For registered members only)
No related posts.
