/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.hyperic.sigar.jartest;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class JarClassTest {
private static final String AGENT_COMMANDS_SERVER_JAR_NAME = "hq-agent-handler-commands";
public static void main(String[] args) {
try {
String libHandlersDir1 = "E:\\HQ\\agent-4.6\\bundles\\agent-4.6\\lib\\handlers";
String libHandlersDir2 = "C:\\Program Files\\hq-plugins";
// 通过JarFile得到Jar文件
File f = getAgentCommandsServerJar(libHandlersDir1);
JarFile jarFile = new JarFile(f);
Manifest manifest = jarFile.getManifest();
String mainClass = manifest.getMainAttributes().
getValue("Main-Class");
System.out.println("Class is: " + mainClass);
String jarPath = f.getAbsolutePath();
System.out.println("jarPath is: " + jarPath);
//通过JarURLConnection得到Jar文件
File[] f2 = getOtherCommandsServerJars(libHandlersDir2);
String path = f2[0].getAbsolutePath();
URL jarUrl = toJarURL(path);
JarURLConnection jarConn = (JarURLConnection) jarUrl.openConnection();
Attributes attrs = jarConn.getMainAttributes();
String pluginName =
attrs.getValue(Attributes.Name.MAIN_CLASS);
System.out.println("JarURLConn " + pluginName);
} catch (Exception ex) {
Logger.getLogger(JarClassTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static String toFileURL(String file) {
//这一步主要是转换空格
// file = StringUtil.replace(file, " ", "%20");
return "file:" + file;
}
private static URL toJarURL(String file)
throws Exception {
return new URL("jar", "", toFileURL(file) + "!/");
}
private static File getAgentCommandsServerJar(String libHandlersDir)
throws Exception {
File[] jars = new File(libHandlersDir).listFiles(new FileFilter() {
public boolean accept(File file) {
String name = file.getName();
return name.startsWith(AGENT_COMMANDS_SERVER_JAR_NAME);
}
});
if (jars == null || jars.length != 1) {
throw new FileNotFoundException(AGENT_COMMANDS_SERVER_JAR_NAME+" jar is not optional");
}
return jars[0];
}
private static File[] getOtherCommandsServerJars(String libHandlersDir) {
File[] jars = new File(libHandlersDir).listFiles(new FileFilter() {
public boolean accept(File file) {
String name = file.getName();
return name.endsWith(".jar") && !name.startsWith(AGENT_COMMANDS_SERVER_JAR_NAME);
}
});
if (jars == null) {
return new File[0];
}
return jars;
}
}
与Jar文件相关类的测试
最新推荐文章于 2024-04-26 15:36:52 发布