在Java编程中,如何使用java从.class
文档中提取内容?
项目的目录结构如下 -
Tika的工具包可从以下网址下载:http://tika.apache.org/download.html ,只下载:tika-app-1.16.jar 和 tika-server-1.16.jar 。
以下是使用java从.class
文档中提取内容的程序 -
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.asm.ClassParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
public class ExtractContentFromJavaClass {
public static void main(String[] args) throws IOException,SAXException, TikaException {
//detecting the file type
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File(
"bin/ExtractContentFromJavaClass.class"));
ParseContext pcontext = new ParseContext();
//Html parser
ClassParser ClassParser = new ClassParser();
ClassParser.parse(inputstream, handler, metadata,pcontext);
System.out.println("Contents of the document:" + handler.toString());
System.out.println("Metadata of the document:");
String[] metadataNames = metadata.names();
for(String name : metadataNames) {
System.out.println(name + " : " + metadata.get(name));
}
}
}
执行上面示例代码,得到以下结果 -
Contents of the document:public synchronized class ExtractContentFromJavaClass {
public void ExtractContentFromJavaClass();
public static void main(String[]) throws java.io.IOException, org.xml.sax.SAXException, org.apache.tika.exception.TikaException;
}
Metadata of the document:
dc:title : ExtractContentFromJavaClass
resourceName : ExtractContentFromJavaClass.class
title : ExtractContentFromJavaClass