1 7 8 package org.gjt.jclasslib.io; 9 10 import org.gjt.jclasslib.structures.*; 11 12 import java.io.*; 13 import java.util.jar.JarEntry ; 14 import java.util.jar.JarFile ; 15 16 23 public class ClassFileReader { 24 25 private ClassFileReader() { 26 } 27 28 38 public static ClassFile readFromClassPath(String [] classPath, String packageName, String className) 39 throws InvalidByteCodeException, IOException 40 { 41 42 String relativePath = packageName.replace('.', File.separatorChar) + (packageName.length() == 0 ? "" : File.separator) + className + ".class"; 43 String jarRelativePath = relativePath.replace(File.separatorChar, '/'); 44 for (int i = 0; i < classPath.length; i++) { 45 File currentClassPathEntry = new File (classPath[i]); 46 if (!currentClassPathEntry.exists()) { 47 continue; 48 } 49 if (currentClassPathEntry.isDirectory()) { 50 File testFile = new File (currentClassPathEntry, relativePath); 51 if (testFile.exists()) { 52 return readFromFile(testFile); 53 } 54 } else if (currentClassPathEntry.isFile()) { 55 JarFile jarFile = new JarFile (currentClassPathEntry); 56 try { 57 JarEntry jarEntry = jarFile.getJarEntry(jarRelativePath); 58 if (jarEntry != null) { 59 return readFromInputStream(jarFile.getInputStream(jarEntry)); 60 } 61 } finally { 62 jarFile.close(); 63 } 64 } 65 } 66 67 return null; 68 } 69 70 77 public static ClassFile readFromFile(File file) 78 throws InvalidByteCodeException, IOException 79 { 80 81 return readFromInputStream(new FileInputStream(file)); 82 } 83 84 93 public static ClassFile readFromInputStream(InputStream is) 94 throws InvalidByteCodeException, IOException 95 { 96 97 DataInputStream in = new DataInputStream( 98 new BufferedInputStream(is)); 99 100 ClassFile classFile = new ClassFile(); 101 classFile.read(in); 102 in.close(); 103 return classFile; 104 } 105 106 111 public static void main(String [] args) throws Exception { 112 113 final int maxCount = 500; 114 long startTime, endTime; 115 116 File file = new File (args[0]); 117 ClassFile classFile = readFromFile(file); 118 119 startTime = System.currentTimeMillis(); 120 for (int i = 0; i < maxCount; i++) { 121 classFile = readFromFile(file); 122 } 123 endTime = System.currentTimeMillis(); 124 System.out.println("With attributes:"); 125 System.out.print((endTime - startTime)); 126 System.out.println(" ms"); 127 128 System.setProperty(AttributeInfo.SYSTEM_PROPERTY_SKIP_ATTRIBUTES, "true"); 129 startTime = System.currentTimeMillis(); 130 for (int i = 0; i < maxCount; i++) { 131 classFile = readFromFile(file); 132 } 133 endTime = System.currentTimeMillis(); 134 System.out.println("Without attributes:"); 135 System.out.print((endTime - startTime)); 136 System.out.println(" ms"); 137 138 } 139 140 } 141 | Popular Tags |