• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java读取classpath/package/jar下面任意文件

武飞扬头像
曾昌
帮助1

1.读取classpath下面任意文件(可以读取properties文件,也可以是任意其他类型的文件),废话 不多说,直接上代码:

  1.  
    // 读取classpath下面任意文件
  2.  
    URL url = ClassLoader.getSystemResource("one.properties");
  3.  
    // url.getFile() 得到这个文件的绝对路径 /D:/work/workspace/spring-datasource/target/classes/one.properties
  4.  
    InputStream inputStream = new FileInputStream(url.getPath());
  5.  
    Properties properties = new Properties();
  6.  
    properties.load(inputStream);
  7.  
     
  8.  
    for (Map.Entry<Object, Object> objectObjectEntry : properties.entrySet()) {
  9.  
    System.out.println(objectObjectEntry.getKey() ":" objectObjectEntry.getValue());
  10.  
    }
  11.  
     
  12.  
    System.out.println(ClassLoader.getSystemResourceAsStream("one.properties"));
  13.  
     
  14.  
    ClassLoader classLoader = MyTest.class.getClassLoader();
  15.  
    System.out.println(classLoader.getResourceAsStream("one.properties"));
  16.  
    System.out.println(classLoader.getResource("one.properties"));
  17.  
    System.out.println(MyTest.class.getResource("/one.properties"));
  18.  
    System.out.println(MyTest.class.getResourceAsStream("/one.properties"));
学新通

执行效果如下:

学新通

2.读取一个package路径下面所有的class,代码如下:

  1.  
    List<Class> fromPackage = getClasssFromPackage("com.laozeng.test");
  2.  
    for (Class aClass : fromPackage) {
  3.  
    System.out.println(aClass.getName());
  4.  
    }
  5.  
     
  6.  
     
  7.  
    /**
  8.  
    * 获得包下面的所有的class
  9.  
    * @param pack package完整名称
  10.  
    * @return List包含所有class的实例
  11.  
    */
  12.  
    public static List<Class> getClasssFromPackage(String pack) {
  13.  
    List<Class> clazzs = new ArrayList<>();
  14.  
     
  15.  
    // 是否循环搜索子包
  16.  
    boolean recursive = true;
  17.  
     
  18.  
    // 包名字
  19.  
    String packageName = pack;
  20.  
    // 包名对应的路径名称
  21.  
    String packageDirName = packageName.replace('.', '/');
  22.  
     
  23.  
    Enumeration<URL> dirs;
  24.  
     
  25.  
    try {
  26.  
    dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
  27.  
    while (dirs.hasMoreElements()) {
  28.  
    URL url = dirs.nextElement();
  29.  
     
  30.  
    String protocol = url.getProtocol();
  31.  
     
  32.  
    if ("file".equals(protocol)) {
  33.  
    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
  34.  
    findClassInPackageByFile(packageName, filePath, recursive, clazzs);
  35.  
    } else if ("jar".equals(protocol)) {
  36.  
    System.out.println("jar类型的扫描");
  37.  
    }
  38.  
    }
  39.  
     
  40.  
    } catch (Exception e) {
  41.  
    e.printStackTrace();
  42.  
    }
  43.  
     
  44.  
    return clazzs;
  45.  
    }
  46.  
     
  47.  
    /**
  48.  
    * 在package对应的路径下找到所有的class
  49.  
    *
  50.  
    * @param packageName
  51.  
    * package名称
  52.  
    * @param filePath
  53.  
    * package对应的路径
  54.  
    * @param recursive
  55.  
    * 是否查找子package
  56.  
    * @param clazzs
  57.  
    * 找到class以后存放的集合
  58.  
    */
  59.  
    public static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive, List<Class> clazzs) {
  60.  
    File dir = new File(filePath);
  61.  
    if (!dir.exists() || !dir.isDirectory()) {
  62.  
    return;
  63.  
    }
  64.  
    // 在给定的目录下找到所有的文件,并且进行条件过滤
  65.  
    File[] dirFiles = dir.listFiles(file -> {
  66.  
    boolean acceptDir = recursive && file.isDirectory();// 接受dir目录
  67.  
    boolean acceptClass = file.getName().endsWith("class");// 接受class文件
  68.  
    return acceptDir || acceptClass;
  69.  
    });
  70.  
     
  71.  
    for (File file : dirFiles) {
  72.  
    if (file.isDirectory()) {
  73.  
    findClassInPackageByFile(packageName "." file.getName(), file.getAbsolutePath(), recursive, clazzs);
  74.  
    } else {
  75.  
    String className = file.getName().substring(0, file.getName().length() - 6);
  76.  
    try {
  77.  
    clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(packageName "." className));
  78.  
    } catch (Exception e) {
  79.  
    e.printStackTrace();
  80.  
    }
  81.  
    }
  82.  
    }
  83.  
    }
学新通

效果如下:

学新通

3.获取jar文件包中的package下面的所有class,代码如下:

  1.  
    List<Class> fromJarFile = getClasssFromJarFile("D:\\work\\myrep\\com\\alibaba\\druid\\1.2.14\\druid-1.2.14.jar", "com/alibaba/druid/wall");
  2.  
    fromJarFile = getClasssFromJarFile("D:\\work\\myrep\\com\\alibaba\\druid\\1.2.14\\druid-1.2.14.jar", null);
  3.  
    for (Class aClass : fromJarFile) {
  4.  
    System.out.println(aClass.getName());
  5.  
    }
  6.  
     
  7.  
    /**
  8.  
    * 从jar文件中读取指定目录下面的所有的class文件
  9.  
    *
  10.  
    * @param jarPaht jar文件存放的位置
  11.  
    * @param filePaht 指定的文件目录
  12.  
    * @return 所有的的class的对象
  13.  
    */
  14.  
    public static List<Class> getClasssFromJarFile(String jarPaht, String filePaht) {
  15.  
    List<Class> clazzs = new ArrayList<>();
  16.  
     
  17.  
    JarFile jarFile = null;
  18.  
    try {
  19.  
    jarFile = new JarFile(jarPaht);
  20.  
    } catch (IOException e1) {
  21.  
    e1.printStackTrace();
  22.  
    }
  23.  
     
  24.  
    List<JarEntry> jarEntryList = new ArrayList<>();
  25.  
     
  26.  
    Enumeration<JarEntry> ee = jarFile.entries();
  27.  
    while (ee.hasMoreElements()) {
  28.  
    JarEntry entry = ee.nextElement();
  29.  
    if (Objects.equals(filePaht, null)) {
  30.  
    if (entry.getName().endsWith(".class")) {
  31.  
    jarEntryList.add(entry);
  32.  
    }
  33.  
    } else {
  34.  
    // 过滤我们出满足我们需求的东西
  35.  
    if (entry.getName().startsWith(filePaht) && entry.getName().endsWith(".class")) {
  36.  
    jarEntryList.add(entry);
  37.  
    }
  38.  
    }
  39.  
    }
  40.  
    for (JarEntry entry : jarEntryList) {
  41.  
    String className = entry.getName().replace('/', '.');
  42.  
    className = className.substring(0, className.length() - 6);
  43.  
    // 也可以采用如下方式把类加载成一个输入流
  44.  
    // InputStream in = jarFile.getInputStream(entry);
  45.  
    try {
  46.  
    // com.alibaba.druid.support.calcite.TDDLSqlSelect 加载类的时候,也会随之加载类中的其他类,这个时候会报错:Caused by: java.lang.ClassNotFoundException: org.apache.calcite.sql.SqlSelect
  47.  
    System.out.println(className);
  48.  
    clazzs.add(Thread.currentThread().getContextClassLoader()
  49.  
    .loadClass(className));
  50.  
    } catch (Exception e) {
  51.  
    e.printStackTrace();
  52.  
    }
  53.  
    }
  54.  
     
  55.  
    return clazzs;
  56.  
    }
学新通

效果如下:

学新通

4.读取当前工程下面所有jar和classpath下面指定的配置文件(这也是spring加载配置文件的原理),代码如下:

  1.  
    Properties properties = load("META-INF/spring.handlers");
  2.  
    for (Map.Entry<Object, Object> objectObjectEntry : properties.entrySet()) {
  3.  
    System.out.println(objectObjectEntry.getKey() ":" objectObjectEntry.getValue());
  4.  
    }
  5.  
     
  6.  
     
  7.  
    private static Properties load(String resourceName) throws Exception{
  8.  
    Enumeration<URL> urls = ClassLoader.getSystemResources(resourceName);
  9.  
    Properties props = new Properties();
  10.  
    while (urls.hasMoreElements()) {
  11.  
    URL url = urls.nextElement();
  12.  
    URLConnection con = url.openConnection();
  13.  
    ResourceUtils.useCachesIfNecessary(con);
  14.  
    InputStream is = con.getInputStream();
  15.  
    props.load(is);
  16.  
    is.close();
  17.  
    }
  18.  
    return props;
  19.  
    }
学新通

 效果如下,可以看到本工程里面的也加载出来了:

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhaccc
系列文章
更多 icon
同类精品
更多 icon
继续加载