• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 581
  • Last Modified:

URGENT: How to open MS Word using Java

Hi i need my program to open a new MS Word and i found the following code in previous questions. It compiles and run just fine. No errors no exceptions at all. The problem is not opening anything
package test;
 
import java.io.IOException;
 
/**
* FileHanlder opens a native file using the windows shell
*/
public class FileHandler {
 
public static void main(String[] args) {
FileHandler fileHandler = new FileHandler();
fileHandler.displayFile("WINWORD");
}
 
protected void displayFile(String fileName) {
 
// create a string buffer for building our command
StringBuffer cmd = new StringBuffer();
 
// prepare the command to be executed using the windows shell
cmd.append(" rundll32 url.dll,FileProtocolHandler ");
cmd.append(" file://");
cmd.append(fileName);
 
try {
 
Process p = Runtime.getRuntime().exec(cmd.toString());
try {
int exitCode = p.waitFor();
if (exitCode != 0) {
// command failed .. do error handling
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
 
} catch (IOException e) {
System.out.println("Could not execute command: " + cmd);
}
 
}
}

Open in new window

0
nvlachos
Asked:
nvlachos
  • 3
  • 2
1 Solution
 
CEHJCommented:
Try replacing

>>
cmd.append(" rundll32 url.dll,FileProtocolHandler ");
cmd.append(" file://");
cmd.append(fileName);
>>

with

cmd.append("cmd.exe /C start ");
cmd.append(fileName);

Open in new window

0
 
nvlachosAuthor Commented:
Cheers mate!
0
 
CEHJCommented:
:-)
0
 
nvlachosAuthor Commented:
What if i want to open an existing MS Word file instead of a new one?
0
 
CEHJCommented:
Just pass an existing file as fileName. Please delete your new Q - it's not necessary
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now