2014-01-06 53 views
0

我需要檢索我的vaadin 7網絡應用程序中使用的資源的URL,在我的情況下,資源是 圖像可以位於VAADIN/themes/themename/img文件夾或它可以創建一個jar文件。如何檢索服務器中的圖像資源位置

所以我想寫的方法有此簽名:

/** 
    * Returns the URL for an image described with its name 
    */ 
    public String getURL(String image) { 
     ... 
    } 

回答

0

可能因爲罐子是緩慢的。
您應該先填寫您想要的文件類型的列表。

public String getURL(String image) { 
    String realPath = VaadinServlet.getCurrent().getServletContext().getRealPath("/"); 
    List<String> list = new ArrayList<String>(); 
    search(image, new File(realPath), realPath, "", list); 
    if (list.isEmpty()) { 
     return null; // or error message 
    } 
    VaadinServletRequest r = (VaadinServletRequest) VaadinService.getCurrentRequest(); 
    return r.getScheme() + "://" + r.getServerName() + ":" + r.getServerPort() 
      + r.getContextPath() + list.get(0); // or return all 
} 

private void search(String image, File file, String fullPath, String relPath, List<String> list) { 
    if (file.isDirectory()) { 
     for (String subFile : file.list()) { 
      String newFullPath = fullPath + "/" + subFile; 
      search(image, new File(newFullPath), newFullPath, relPath + "/" + subFile, list); 
     } 
    } else { 
     if (image.equals(file.getName())) { 
      list.add(relPath); 
     } 
     if (file.getName().endsWith(".jar")) { 
      ZipInputStream zis = null; 
      try { 
       zis = new ZipInputStream(new FileInputStream(fullPath)); 
       ZipEntry entry = null; 
       while ((entry = zis.getNextEntry()) != null) { 
        String name = entry.getName(); 
        if (name.equals(image) || name.endsWith("/" + image)) { 
         list.add("/" + name); 
        } 
       } 
      } catch (Exception e) { 
       // error handling 
      } finally { 
       IOUtils.closeQuietly(zis); 
      } 
     } 
    } 
} 
相關問題