在最近发布(Java 6.0)
评论,Java提供了桌面级。该类的目的是在系统中打开与给定文件关联的应用程序。因此,如果您使用Word文档(.doc)调用open()方法,那么它会自动调用MS Word,因为这是与.doc文件关联的应用程序。
我已经开发了一个小的Swing程序(尽管你可以开发它作为控制台应用程序)从用户获取文档编号并将文档调用到MSWord
。这个假设是;文件与filename
一起存储,由<document number>>.doc
组成。
下面给出的是您可以编译并按原样运行的Java程序。确保将DIR变量更改为存储.doc文件的文件夹。
这里是在Java中打开Word文档的代码...它的提取物净....
import java.io.File;
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");
initComponents();
}
private void initComponents() {
jLabel1 = new JLabel();
txtDocNumber = new JTextField();
btnOpen = new JButton();
Container c = getContentPane();
c.setLayout(new java.awt.FlowLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Enter Document Number : ");
c.add(jLabel1);
txtDocNumber.setColumns(5);
c.add(txtDocNumber);
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");
desktop.open(f); // 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);
}
}
});
c.add(btnOpen);
} // initCompnents()
public static void main(String args[]) {
WordDocument wd = new WordDocument();
wd.setSize(300,100);
wd.setVisible(true);
}
}
这一切都在这里:http://support.microsoft.com/kb/210565 – assylias