首页 > 解决方案 > Linux平台jdk8生成jar,Windows平台通过jarFile.getJarEntry("pacakge_name")总是返回null

问题描述

  1. HelloWorld.java

     package com.perjoker;
     public class HelloWorld {
     public static void main(String[] args) {
         System.out.println("HelloWorld");
     }
     }
    
  2. javac com/perjoker/HelloWorld.java

  3. jar cvf Hello.jar com/perjoker/HelloWorld.class

  4. 将 Hello.jar 复制到 windows

  5. 下面的代码在windows平台上执行时总是返回null,非常混乱。如果在windows平台生成Hello.jar,以下代码可以正确返回

    JarFile jarFile = new JarFile("Hello.jar");
    JarEntry jarEntry = jarFile.getJarEntry("com/perjoker");

标签: java

解决方案


  • 这是jar命令的两种使用方式

    jar --help 
    Example 1: to archive two class files into an archive called classes.jar:
           jar cvf classes.jar Foo.class Bar.class
    Example 2: use an existing manifest file 'mymanifest' and archive all the
               files in the foo/ directory into 'classes.jar':
           jar cvfm classes.jar mymanifest -C foo/ .
    
    
    • 例1:生成jar包时会没有目录信息,如下图

      λ jar tf Hello_WSL.jar
      META-INF/
      META-INF/MANIFEST.MF
      com/perjoker/HelloWorld.class
      
    • 例2:会生成带有目录信息的jar包,如下图

      λ jar tf Hello_windows.jar
      META-INF/
      META-INF/MANIFEST.MF
      com/
      com/perjoker/
      com/perjoker/HelloWorld.class
      com/perjoker/HelloWorld.java
      

因此,如果使用示例 2 生成 jar,则没有问题。


推荐阅读