9

I want to launch a file(a document) from a Java program and phase the following requirements:

  • Method must be applicabale on Mac, Win and Linux systems
  • I am not allowed to use "Runtime.getRuntime().exec("cmd.exe /C +"filename");
  • The file I am launching needs to be either of .doc / .docx / .rtf

The file is created runtime, a result from a report being created. Any good practices?

Tor-Morten
  • 1,522
  • 2
  • 12
  • 19
  • I'm not sure to understand what launch a file means...do you have a constraint concerning the program opening the file ? do you want to launch a particular application with your file opened ? Are you sure that all the machines you're running your program on will have a program supporting .doc files ? – LB40 May 11 '09 at 13:13
  • Launch, in this context, means to open the file with the associated program. Yes, I have a guarantee of having a program supporting .doc – Tor-Morten May 11 '09 at 13:36

2 Answers2

23

Use Java Desktop API.

Desktop.getDesktop().open(new File(yourfilename));
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
5

If you're running 1.6, use the Desktop API per mad-j's advice. If you're using an older VM (1.5 or earlier) you'll need to write your own platform-specific code to do this.

On the mac,

Runtime.getRuntime().exec(new String[] {"open", pathToFile});

On windows,

Runtime.getRuntime().exec(new String[] {"cmd.exe", "/C", pathToFile});

You may need to escape the path on windows.

Sam Barnum
  • 10,559
  • 3
  • 54
  • 60