我想用JAVA做一个电子书阅读器,我想添加读WORD文件的功能,安装了jacob且能工作,现在我想把WORD文件的内容输出到textArea1上面(是一个JTextArea)下面是我的读文件的代码,请大虾看下,不知道为什么读不出来!
 public void jButton1_actionPerformed(ActionEvent e) {
    fd=new FileDialog(this,"打开",FileDialog.LOAD);
    fd.setVisible(true);    strFile=fd.getDirectory()+fd.getFile();
    File file=new File(strFile);
    int size=(int)file.length();    if (strFile != null) {     String filetype = new String("");
     String filename = strFile;
     filetype = filename.substring((filename.length() - 3), filename.length());
     if(filetype.equals("txt")){
      try {
        FileInputStream fis=new FileInputStream(strFile);
                 byte[] buf=new byte[size];
                 int len=fis.read(buf);
                 textArea1.append(new String(buf,0,len));
                 statusBar.setText("打开:"+fd.getFile());
                 fis.close();
               }
      catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    else if (filetype.equals("doc")) {
      ActiveXComponent app = new ActiveXComponent("Word.Application");
      String docpath = strFile;
      String inFile = docpath;
      String tpFile = strFile.substring(0, (filename.length() - 4));
      boolean flag = false;
      try {        app.setProperty("Visible", new Variant(false));
        Dispatch docs = app.getProperty("Documents").toDispatch();
        Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
                                       new Object[] {inFile, new Variant(false),
                                       new Variant(true)}
                                       , new int[1]).toDispatch();
        //打开word文件
        Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
                        new Object[] {tpFile, new Variant(8)}
                        , new int[1]);
        Variant f = new Variant(false);
        Dispatch.call(doc, "Close", f);
        flag = true;        FileInputStream fis = new FileInputStream(tpFile);
        byte[] buf = new byte[size];
        int len = fis.read(buf);
        textArea1.append(new String(buf, 0, len));
        statusBar.setText("打开:" + fd.getFile());
        fis.close();      }
      catch (Exception ex) {      }    }
  }
    }

解决方案 »

  1.   

    1.String tpFile = strFile.substring(0, (filename.length() - 4));
    加上+".html"
    2.我打开是时候是这样
    Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[]{inFile},new int[1]).toDispatch();或者更简单Dispatch.call(docs,   "Open",   inFile).toDispatch();
    3.app.setProperty("Visible", new Variant(false));中的false改成true的话可以看到打开的word,这样更好判断,或者你在其它地方输出一些什么信息,就好判断哪里出问题了
    4.Dispatch.call(doc, "Close", f);改成app.invoke("Quit",new Variant[]{});好点,不然的话你会发现那个进程还没关掉,前面那个关闭就只是关闭你编辑的word,后面那个word就是把整个word关闭.