Srikanth Technologies

Opening MSWord Document From Java

A student has asked me regarding, "how to open MS Word document from Java". I have decided to put a blog that shows how to do it. It could be useful even for other purposes that are similar to this.

In the recent release (Java 6.0), Java provides Desktop class. The purpose of the class is to open the application in your system that is associated with the given file. So, if you invoke open() method with a Word document (.doc) then it automatically invokes MS Word as that is the application associated with .doc files.

I have developed a small Swing program (though you can develop it as a console application) to take document number from user and invoke document into MSWord. The assumption is; documents are stored with filename consisting of <document number>>.doc.

Given below is the Java program that you can compile and run as-it-is. Make sure you change DIR variable to the folder where .doc files are stored.

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class WordDocument extends JFrame {
    private JButton btnOpen;
    private JLabel jLabel1;
    private JTextField txtDocNumber;
    private static String DIR  ="c:\\worddocuments\\";   // folder where word documents are present.
    public WordDocument() {
       super("Open Word Document");
    private void initComponents() {
        jLabel1 = new JLabel();
        txtDocNumber = new JTextField();
        btnOpen = new JButton();
        Container c = getContentPane();
        c.setLayout(new java.awt.FlowLayout());
        jLabel1.setText("Enter Document Number  : ");
        btnOpen.setText("Open Document");
        btnOpen.addActionListener(new ActionListener() {      // anonymous inner class 
            public void actionPerformed(ActionEvent evt) {
                  Desktop desktop = Desktop.getDesktop();  
	          try {
	            File f = new File( DIR + txtDocNumber.getText()  +  ".doc");;  // opens application (MSWord) associated with .doc file
	          catch(Exception ex) {
				// WordDocument.this is to refer to outer class's instance from inner class
	            JOptionPane.showMessageDialog(WordDocument.this,ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
    } // initComponents()
    public static void main(String args[]) {
          WordDocument wd = new WordDocument();

Post Your Comment


Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :