Extract Content from Java Class File


Advertisements

Problem Description

How to extract content from a java .class file using java.

Solution

Following is the program to extract content from a java .class file using java.

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(
         "C:/tika/classFileExample.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));   
      }
   }
}

Input

Class File Example

Output

Contents of the document:public synchronized class ClassFileExample { 
   public void ClassFileExample(); 
   public static void main(String[]); 
}   

Metadata of the document: 
dc:title :  ClassFileExample 
resourceName :  ClassFileExample.class 
title :  ClassFileExample
java_apache_tika
Advertisements