O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 like this:
open 'Current Notes.txt'
Unfortunately, quotes won’t work when you call open from a program
because the quotes are actually interpreted by the user’s command-line
shell, not
open itself. When you call open directly from a program, you are
bypassing the shell and lose quote interpolation. The solution is to break the
command line into an array of arguments manually. That way
open knows
what is a space and what is the gap between arguments:
Runtime rt = Runtime.getRuntime( );
String[] cmd = {"open", "Current Notes.txt"};
rt.exec(cmd);
Now, you might wonder why open needs to distinguish between argument
gaps and real spaces when it takes only one argument to begin with.
open

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required