1

I am trying to open *.docx files programmatically from Java on Mac OS X. For Windows and Linux I already got it working with the following methods:

Windows:

Runtime.getRuntime().exec(new String[] {"C:\Program Files\Microsoft Office\Office15\WINWORD.EXE", "document.docx"});

Linux:

Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", "/usr/bin/libreoffice", "document.docx"});

How does it work with Mac OS X ? My Microsoft Office installation is at the following location:

/Applications/Microsoft Office 2011/Microsoft Word.app

Any ideas highly appreciated - thanks.

salocinx
  • 3,715
  • 8
  • 61
  • 110
  • What if I have OpenOffice or StarOffice instead of LibreOffice? What if I've installed mine in /usr/local/bin/ or /opt/local/bin? On windows, the location "C:\Program Files\" is actually configurable and is represented by an environment variable. Maybe a company has set up S:\SharedPrograms on a SAN. These kinds of assumptions are almost always made and are almost always right, but fail completely for some part of the audience/market. – Stephen P Aug 06 '14 at 21:55
  • Hi Stephen - thanks for your comment. My example above is intentionally highly simplified in order to define the core problem. The program paths in my application are completely user configurable. Moreover the user can link arbitrary external programs with any data types and my application then maps the data type with the corresponding program to open the file. – salocinx Aug 07 '14 at 11:00

2 Answers2

5

You can open it in all three operating systems using the Java Desktop API:

File myFile = new File("/path/to/mydoc.docx");
Desktop.getDesktop().open(myFile);
martinez314
  • 12,162
  • 5
  • 36
  • 63
  • 1
    You may want to check `Desktop.isDesktopSupported()` and `GraphicsEnvironment.isHeadless()` before calling `Desktop.getDesktop()`, or be ready to catch the UnsupportedOperationException and HeadlessException that getDesktop can throw. – Stephen P Aug 06 '14 at 21:47
  • Yes, that is exactly the strategy I implemented so far. First trying to open the file with Desktop.open() - and if this fails, the user can link a specific data type with any program (i.e. open with Runtime.exec()). – salocinx Aug 07 '14 at 11:06
3

There is a program called open (/usr/bin/open), which accepts -a for an application, and also files passed, so you can do something like:

Runtime.getRuntime().exec(new String[] {"open", "-a", "Microsoft Word", "document.docx"});
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122