How to open file in Microsoft Word on Mac OS X from within Java?
Asked Answered
I

2

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.

Irriguous answered 6/8, 2014 at 15:14 Comment(2)
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.Hypodermis
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.Irriguous
S
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"});
Shirlshirlee answered 6/8, 2014 at 15:26 Comment(0)
I
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);
Illaffected answered 6/8, 2014 at 21:35 Comment(2)
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.Hypodermis
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()).Irriguous
S
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"});
Shirlshirlee answered 6/8, 2014 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.