2011-01-14 76 views
3

我有一个包含一个svnversion.properties文件(只是看起来像svnversion=12345M或其他)和下面的静态方法在class SVNVersionfoo.jar的java:获得正确的资源

public static SVNVersion fromString(String s) { ... } 
public static SVNVersion fromResources(Class<?> cl) { 
    ResourceBundle svnversionResource = ResourceBundle.getBundle(
     "svnversion", Locale.getDefault(), cl.getClassLoader()); 
    if (svnversionResource.containsKey("svnversion")) 
    { 
     String svnv = svnversionResource.getString("svnversion"); 
     return fromString(svnv); 
    } 
    else 
    { 
     return null; 
    } 
} 

我也有一个图书馆bar.jar那还包含一个svnversion.properties文件(假设它包含svnversion=789)。

然而,当我运行一个class SomeClassInBarJar这是在bar.jar中的以下:

SVNVersion vfoo = SVNVersion.fromResources(SVNVersion.class); 
SVNVersion vbar = SVNVersion.fromResources(SomeClassInBarJar.class); 

我打印结果,我看到789两次。很明显,我没有这样做。如何在包含给定类的jar文件的根目录中获取正确的svnversion.properties文件? (假设它的存在)


编辑:我只是想

InputStream is = cl.getResourceAsStream("/svnversion.properties"); 

,它有同样的问题。我似乎只能访问主jar文件的/svnversion.properties而不是库的/svnversion.properties

+1

给不同的类名并不一定意味着不同的类加载器。我不认为这是可能的,这样做 – 2011-01-14 18:27:09

+0

@Teja:我明白了。 :-)我对如何正确地做它感兴趣。 – 2011-01-14 18:28:47

回答

2

你显然不能使用这种方法,因为无论svnversion.properties文件是否总会用到类加载器。这与您将看到的类相同:如果具有相同名称的两个类位于类路径中,则无论先使用哪个类。

A(曲)的方法是找出罐子类属,然后在罐子检索svnversion.properties

public static JarFile getJarFile(Class<?> cl) { 
    URL classUrl = cl.getResource(cl.getSimpleName() + ".class"); 
    if (classUrl != null) { 
     try { 
      URLConnection conn = classUrl.openConnection(); 
      if (conn instanceof JarURLConnection) { 
       JarURLConnection connection = (JarURLConnection) conn; 
       return connection.getJarFile(); 
      } 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
    return null; 
} 

public static SVNVersion fromResources(Class<?> cl) { 
    JarFile jarFile = getJarFile(cl); 
    ZipEntry entry = jarFile.getEntry("svnversion.properties"); 
    Properties props = new Properties(); 
    try { 
     props.load(jarFile.getInputStream(entry)); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 

    if (props.containsKey("svnversion")) { 
     String svnv = props.getProperty("svnversion"); 
     return fromString(svnv); 
    } else { 
     return null; 
    } 
} 

这就是为什么,恕我直言,你可能会更好存储svn版本号本身作为最终的静态变量(并使用svn $Revision$关键字)。