簡體   English   中英

如何訪問jar中的資源,它可以存在於多個jar中

[英]How to access resources in jar where it can be present in multiple jar

我有一個項目,我可以針對許多XSD生成大量代碼。 為了使事物分離,每組XSD在項目中捆綁在一起。 我有多個項目,它將在資源中看到XSD並生成針對它們的代碼。

我的問題是當我嘗試訪問存儲在jar文件中的XSD時,我無法從一個特定的jar中獲取訪問XSD的代碼。 相反,無論jar如何,它都將訪問與標准匹配的第一個XSD。

這是我用來列出資源的代碼,所有的jar都具有相同的結構,這意味着XSD總是存儲在jar文件根目錄的xsd文件夾中。 下面的代碼列出了文件夾中的XSD。

URL dirURL = clazz.getClassLoader().getResource(path);
  System.out.println(dirURL.toURI());
  if (dirURL != null && dirURL.getProtocol().equals("file")) {
   /* A file path: easy enough */
   System.out.println(dirURL.toURI());
  return new File(dirURL.toURI()).list();
  }

  if (dirURL == null) {
   /* 
    * In case of a jar file, we can't actually find a directory.
    * Have to assume the same jar as clazz.
    */
   String me = clazz.getName().replace(".", "/") + ".class";
   dirURL = clazz.getClassLoader().getResource(me);
   System.out.println(dirURL.toURI());
   System.out.println(me);
  }

  if (dirURL.getProtocol().equals("jar")) {
   /* A JAR path */
   String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
   System.out.println(jarPath);
   JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
   Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
   Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
   String name = null;
   while (entries.hasMoreElements()) {
    name = entries.nextElement().getName();
    if (name.startsWith(path)) { //filter according to the path
     String entry = name.substring(path.length());
     int checkSubdir = entry.indexOf("/");
     if (checkSubdir >= 0) {
      // if it is a subdirectory, we just return the directory name
      entry = entry.substring(0, checkSubdir);
     }
     result.add(entry);
    }
   }
   return result.toArray(new String[result.size()]);

我通常會規定將資源目錄添加到每個JAR中,並使用對其下保存的JAR唯一的資源。 例如(在Maven結構中)

module1/src/main/resources/module1/example.xsd
module2/src/main/resources/module2/example.xsd

然后使用引用XSD

InputStream module1XSD= SomeClass.class.getResourceAsStream("/module1/example.xsd");
InputStream module2XSD= SomeClass.class.getResourceAsStream("/module2/example.xsd");

只要module1和module2的JAR放在包含SomeClass的應用程序的類路徑上。

Spring語境將引用這些作為

classpath:module1/example.xsd,
classpath:module2/example.xsd

這意味着您必須能夠在您生成的JAR中移動XSD的位置。 甚至可能通過構建腳本重新生成它們。

如果XSD都具有相同的名稱,您將需要另一個標准,知道“正確的”是什么。 您是否可以在其中嵌入一些信息(或者使用它,如屬性文件或其他東西)來表明其目的?

並且,獲得它們的更方便的迭代器可能是:

 getClass().getClassLoader().getResources("/file.xsd");

或者其他的東西。 (依賴於類路徑,無論是在文件系統上還是在jar中)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM