11

Possible Duplicate:
Open excel document in java

I have a button in my Java application that, when clicked, should cause Word to open a particular file. This file is residing somewhere in the filesystem, like in a user's documents directory.

How can I implement something like this in Java?

Community
  • 1
  • 1
Sarah
  • 370
  • 1
  • 7
  • 25

2 Answers2

17

Here is the simple Demo App , you can modify it for button click event :

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class Test {
 public static void main(String[] a) {
   try {
     if (Desktop.isDesktopSupported()) {
       Desktop.getDesktop().open(new File("c:\\a.doc"));
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
  }
}

}

This would open word file with default word application . More detail here for Desktop

Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
1

One way is to execute the default program to open the document through the shell.

On Windows:

Process p = Runtime.getRuntime()
                .exec("rundll32 url.dll,FileProtocolHandler C:/Path/To/Word.doc");
p.waitFor();
System.out.println("Done.");

Mac:

Process p = Runtime.getRuntime().exec("open /Documents/word.doc");

From - http://www.rgagnon.com/javadetails/java-0014.html

arunkumar
  • 32,803
  • 4
  • 32
  • 47
  • There is no need to use rundll for Windows: `Runtime.getRuntime().exec("start /Documents/word.doc");`. This assumes that the extension .doc is associated with MS Word. But using the Desktop class is much better as it is platform independent –  Jul 29 '11 at 10:28
  • 1
    @a_horse_with_no_name: I wish you were right. Desktop crashes on some Windows platforms :-( , so this is actually useful. – Nathan Hughes Jul 29 '11 at 10:42
  • 1
    @Nathan Hughes: I have neither heard about that nor did I experience it myself and I've used since Java6 was released. –  Jul 29 '11 at 10:46
  • @a_horse_with_no_name: I had it happen here just a few weeks ago, java.awt.Desktop caused my program to crash on a Windows XP machine. Otherwise I most likely wouldn't take this seriously either. – Nathan Hughes Jul 29 '11 at 13:12