如何用JAVA读取Doc文档

Python07

如何用JAVA读取Doc文档,第1张

word有微软的专用格式,如果要读取其内容,可以使用jar包,如下:

1。用jacob.

其实jacob是一个bridage,连接java和com或者win32函数的一个中间件,jacob并不能直接抽取word,excel等文件,需要自己写dll哦,不过已经有为你写好的了,就是jacob的作者一并提供了。

jacob下载: http://www.matrix.org.cn/down_view.asp?id=13

下载了jacob并放到指定的路径之后(dll放到path,jar文件放到classpath),就可以写你自己的抽取程序了,下面是一个例子:

import java.io.File

import com.jacob.com.*

import com.jacob.activeX.*

public class FileExtracter{

public static void main(String[] args) {

ActiveXComponent app = new ActiveXComponent("Word.Application")

String inFile = "c:\\test.doc"

String tpFile = "c:\\temp.htm"

String otFile = "c:\\temp.xml"

boolean flag = false

try {

app.setProperty("Visible", new Variant(false))

Object docs = app.getProperty("Documents").toDispatch()

Object doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{inFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch()

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

} catch (Exception e) {

e.printStackTrace()

} finally {

app.invoke("Quit", new Variant[] {})

}

}

}

2。用apache的poi来抽取word,excel。

poi是apache的一个项目,不过就算用poi你可能都觉得很烦,不过不要紧,这里提供了更加简单的一个接口给你:

下载经过封装后的poi包: http://www.matrix.org.cn/down_view.asp?id=14

下载之后,放到你的classpath就可以了,下面是如何使用它的一个例子:

import java.io.*

import org.textmining.text.extraction.WordExtractor

/**

*

Title: pdf extraction

*

Description: email:[email protected]

*

Copyright: Matrix Copyright (c) 2003

*

Company: Matrix.org.cn

* @author chris

* @version 1.0,who use this example pls remain the declare

*/

public class PdfExtractor {

public PdfExtractor() {

}

public static void main(String args[]) throws Exception

{

FileInputStream in = new FileInputStream ("c:\\a.doc")

WordExtractor extractor = new WordExtractor()

String str = extractor.extractText(in)

System.out.println("the result length is"+str.length())

System.out.println("the result is"+str)

}

}

import java.util.*

public class Property {

/**

*

* @param args the args is a parative

*/

public static void main(String[] args) {

System.out.println(new Date())

Properties p = System.getProperties()

p.list(System.out)

System.out.println("--- Memory Usage:")

Runtime rt = Runtime.getRuntime()

System.out.println("Total Memory = "

+ rt.totalMemory()

+ " Free Memory = "

+ rt.freeMemory())

}

}

在CMD运行:javac -d docDirectory nameOfPackage(docDirectory是.html保存的路径,nameOfPackage是需要提取注释的包的名称)

如果只要Property类的.htm,在当前目录,则在CMD运行:javac Property.java(已经在Property所在路径)