
412
|
Chapter 11, Native Integration and Packaging
#80 Open Files, Directories, and URLs on Mac OS X
HACK
open has a simple syntax: open filename. By calling it from within your pro-
gram, you can open any file with its default application.
open will start
launching the viewer automatically and return control to your program
immediately. As in Microsoft Windows, you can call the program using
Runtime.exec( )
:
public static void main(String[] args) throws Exception {
Runtime rt = Runtime.getRuntime( );
rt.exec("open notes.txt");
}
This program will open a file in the current directory (notes.txt), in the
default viewer for text files, usually
TextEdit. You can also specify an abso-
lute path for the file:
rt.exec("open /Users/josh/Desktop/notes.txt");
If you pass a directory instead of a file, then OS X will open that directory in
a new Finder window. This can be useful for showing the location of a
recently downloaded file or demonstrating where to install new software:
// open the current working directory
rt.exec("open .");
// open the applications directory
rt.exec("open /Applications");
Finally, you can open any web page using the user’s default web browser
(probably Safari) by calling
open with a URL:
// open Yahoo! in the user's web browser
rt.exec("open http://www.yahoo.com/");
Handle Spaces
Some filepaths may contain spaces. When you run open from the command
line you can escape these spaces using quotes ...