因為微軟沒有公開word原始碼,所以直接用java流來讀取word的後果是讀出來的全是亂碼。所以必須通過jacob這個中間橋 。當然也可用poi來讀取。
先說用poi讀取的方法吧。用poi讀取的話,先要下載tm-extractors-0.4.jar百度一下可以找到。代碼如下:
import org.textmining.text.extraction.WordExtractor;
try {
FileInputStream fileinputstream = new FileInputStream(
filepath);
WordExtractor extractor = new WordExtractor();
temp =extractor.extractText(fileinputstream);
System.out.println(temp+"==temp");
fileinputstream.close();
} catch (Exception ex) {
System.out.println("FileNotFoundException error" +
ex.getMessage());
}
filepath為word文檔路徑,返回一個temp字串。這樣讀出來的不是亂碼了,但是效果並不如意。因為把word格式給丟掉了。
再說用jacob. 先到官方網站上去下載:http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368 jacob.zip. 下載之後解壓,把jacob.jar放到項目/web-inf/lib下面。把jacob .dll放到c:/windos/system32/以及java/jdk*.*/jre/bin下面。這樣就算是配置完成了。說代碼:
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public boolean ChageFormat (String FolderPath,String FileName){
String FileFormat = "";
System.out.println(FolderPath);
FileFormat = FileName.substring(FileName.length()-4,FileName.length());
System.out.println(FileFormat);
if(FileFormat.equalsIgnoreCase(".doc"))
{
String DocFile = FolderPath +"//"+ FileName;
System.out.println("word檔案路徑:"+DocFile);
//word檔案的完整路徑
String HtmlFile = DocFile.substring(0, (DocFile.length() - 4)) + ".htm";
System.out.println("htm檔案路徑:"+HtmlFile);
//html檔案的完整路徑
ActiveXComponent app = new ActiveXComponent("Word.Application");
//啟動word
try
{
app.setProperty("Visible", new Variant(false));
//設定word程式非可視化運行
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{DocFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch();
//開啟word檔案
Dispatch.invoke(doc,"SaveAs",Dispatch.Method, new Object[]{HtmlFile,new Variant(8)}, new int[1]);
//作為htm格式儲存檔案
Dispatch.call(doc, "Close",new Variant(false));
//關閉檔案
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
app.invoke("Quit", new Variant[] {});
//退出word程式
}
//轉化完畢
return true;
}
return false;
}
FolderPath為word存放路徑。FileName為word名稱。通過這個方法就把word檔案轉成的htm檔案。這時候就可以用流來讀取htm檔案了,讀出來的既不是亂碼。並且帶有格式。
另外要強調的是jacob這個組件和jdk,以及windows版本都有關係。所以版本一定要匹配。否則會報錯。版本的問題就要挨個去試了。沒有捷徑可走。