Apache Tika用於文件類型檢測和從各類格式的文件內容提取的庫。apache
將上傳文件至服務器,進行解析文件時,常常須要判斷文件是否損壞。咱們可使用tika來檢測文件是否損壞服務器
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-app</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
若是jar包衝突時能夠引入以下:app
<dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>1.18</version> </dependency> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> <version>1.18</version> </dependency> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.11.0</version> </dependency>
若是從輸入流讀取失敗,則parse方法拋出IOException異常,從流中獲取的文檔不能被解析拋TikaException異常,處理器不能處理事件則拋SAXException異常maven
當文檔不能被解析時,說明文檔損壞測試
public static void main(String[] args) { try { //Assume sample.txt is in your current directory File file = new File("D:\\測試.txt"); boolean result = isParseFile(file); } catch (Exception e) { e.printStackTrace(); } } /** * 驗證文件是否損壞 * * @param file 文件 * @return true/false * @throws Exception */ private static boolean isParseFile(File file) throws Exception { try { Tika tika = new Tika(); String filecontent = tika.parseToString(file); System.out.println(filecontent); return true; } catch (TikaException e) { return false; } }
輸出結果:spa
測試數據---讀取文本內容code