2016-06-13 55 views
0

我正在试图为一个jar文件内的文件找到.class创建时间。 但是当我尝试使用这段代码时,我得到了Jar创建时间而不是.class文件创建时间。一个jar里面的类的最后更新时间

URL url = TestMain.class.getResource("/com/oracle/determinations/types/CommonBuildTime.class"); 
    url.getPath(); 
    try { 
     System.out.println(" Time modified :: "+ new Date(url.openConnection().getLastModified())); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

但是当我打开jar时,我可以看到.class创建时间与jar创建时间不同。

+0

我不知道你想做什么,但你可能会发现包的版本相当容易的工作。例如,'if(CommonBuildTime.class.getPackage()。isCompatibleWith(“2.0”)){assumeNewVersion(); }' – VGR

回答

1

能否请您尝试以下解决方案:

import java.io.IOException; 
import java.util.Date; 
import java.util.Enumeration; 
import java.util.jar.JarEntry; 
import java.util.jar.JarFile; 

public class Test { 

public static void main(String[] args) throws IOException { 
    String classFilePath = "/com/mysql/jdbc/AuthenticationPlugin.class"; 
    String jarFilePath = "D:/jars/mysql-connector-java-5.1.34.jar";  
    Test test=new Test(); 
    Date date = test.getLastUpdatedTime(jarFilePath, classFilePath); 
    System.out.println("getLastModificationDate returned: " + date); 
} 

/** 
* Returns last update time of a class file inside a jar file 
* @param jarFilePath - path of jar file 
* @param classFilePath - path of class file inside the jar file with leading slash 
* @return 
*/ 
public Date getLastUpdatedTime(String jarFilePath, String classFilePath) { 
JarFile jar = null; 
try { 
    jar = new JarFile(jarFilePath); 
    Enumeration<JarEntry> enumEntries = jar.entries(); 
    while (enumEntries.hasMoreElements()) { 
     JarEntry file = (JarEntry) enumEntries.nextElement(); 
     if (file.getName().equals(classFilePath.substring(1))) { 
      long time=file.getTime(); 
      return time==-1?null: new Date(time); 
     } 

    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    if (jar != null) { 
     try { 
      jar.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
return null; 

    } 

}