Using Java, how do I cause Word to open and edit a file?
30,578
Solution 1
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
Solution 2
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
Comments
-
Sarah almost 2 years
Possible Duplicate:
Open excel document in javaI 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?
-
a_horse_with_no_name over 12 yearsThere 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 -
Nathan Hughes over 12 years@a_horse_with_no_name: I wish you were right. Desktop crashes on some Windows platforms :-( , so this is actually useful.
-
a_horse_with_no_name over 12 years@Nathan Hughes: I have neither heard about that nor did I experience it myself and I've used since Java6 was released.
-
Andrew Thompson over 12 years"This would open word file with MS word application ." Not if OO is the default consumer for Word docs. ;) @Sarah You might also want to check out the
edit(File)
method of that same class. -
Sandeep Pathak over 12 years@Andrew : Thanks , Updated ..!!
-
Andrew Thompson over 12 yearsExcellent work. I'd up-vote, but I already did that before. ;)
-
Nathan Hughes over 12 years@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.
-
Krishna about 10 yearsnice tip, it is simple and easy to open a file