Apache tika -- 解析多種型別(word、pdf、txt 等)檔案!
阿新 • • 發佈:2019-01-29
http://cloudera.iteye.com/blog/737629
apache 是個偉大的組織。
在lucene 檢索 如火如荼時, apache不忘繼續努力,近期提供了對各種格式檔案進行解析的解決方案 -- apache旗下的tika. 雖然還沒有1.0版 , 但已經很好用:
Java程式碼- /**
- * 解析各種型別檔案
- * @param 檔案路徑
- * @return 檔案內容字串
- */
- public static String parse(String path) {
-
String result = ""
- TikaConfig tikaConfig = TikaConfig.getDefaultConfig();
- try {
- result = ParseUtils.getStringContent(new File(path), tikaConfig);
- }catch (Exception e) {
- log.debug("[by ninja.hzw]" + e);
- }
- return result;
- }
很簡單,可以解析各種檔案,返回文件內容字串, word2003/2007 、 pdf 、 txt 都經過測試,均能解析且無亂碼問題。
oh, Great Apach
Tika 的下載和打包:
下載不用多說,google 一下“apache tika” 找到其官網下載即可。
Java程式碼- To build Tika from sources you first need to either download a source release or checkout the latest sources from version control.
-
Once you have the sources, you can build them using the Maven 2 build system. Executing the following command in the base directory will build the sources and install the resulting artifacts in your local Maven repository.
- mvn install
apache 已經說得很清楚,進入下載後的tika 目錄 ,然後執行maven install 即可。(當然這裡需要您懂得maven2的使用。當然不會的朋友可以聯絡我^^ . 還需注意,必須為jdk1.5 + 才能成功編譯打包。)
打包完後產生以下 jar:
Java程式碼- tika-core/target/tika-core-0.7.jar
- Tika core library. Contains the core interfaces and classes of Tika, but none of the parser implementations. Depends only on Java 5.
- tika-parsers/target/tika-parsers-0.7.jar
- Tika parsers. Collection of classes that implement the Tika Parser interface based on various external parser libraries.
- tika-app/target/tika-app-0.7.jar
- Tika application. Combines the above libraries and all the external parser libraries into a single runnable jar with a GUI and a command line interface.
- tika-bundle/target/tika-bundle-0.7.jar
- Tika bundle. An OSGi bundle that includes everything you need to use all Tika functionality in an OSGi environment.
我們要想做文件解析,只需引入tika-core 和 tika-parsers 即可。
當然如果您的專案是maven 構建的,那更好了。在pom里加上依賴:
Java程式碼- <dependency>
- <groupId>org.apache.tika</groupId>
- <artifactId>tika-core</artifactId>
- <version>0.7</version>
- </dependency>
以及
Java程式碼- <dependency>
- <groupId>org.apache.tika</groupId>
- <artifactId>tika-parsers</artifactId>
- <version>0.7</version>
- </dependency>
maven 會自動下載。(感謝maven官方的支援。)