【问题标题】:How to Read PNG from a jar packaged in a war如何从战争中打包的 jar 中读取 PNG
【发布时间】:2014-09-23 09:17:34
【问题描述】:

我正在尝试编写一些代码,允许我访问一个文件(特别是 EMailBanner.png),该文件被包装为一个 jar,然后包含在一个战争中。

我拼凑的代码如下;

public static File getFile(String imagePath){

    if(StringUtilities.stringEmptyOrNull(imagePath)){
        throw new IllegalArgumentException("Invalid image path");
    }

    File tempFile = null;
    InputStream is = null;
    FileOutputStream fos = null;
    try{
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        is = classLoader.getResourceAsStream(imagePath);
        tempFile = File.createTempFile("EMailBanner", ".png"); 
        tempFile.deleteOnExit();  
        fos = new FileOutputStream(tempFile); 
        byte[] buf = new byte[1024];  
        int len;  
        while ((len = is.read(buf)) != -1) {  
            fos.write(buf, 0, len);  
        }
    }catch(IOException e ){
        LOGGER.error("Unable to load image", e);
    }catch(Exception e){
        LOGGER.error("Unable to load image", e);
    }finally{
        try {   
            fos.close();
            is.close();
        } catch (IOException e) {
            LOGGER.warn("Unable to close the file input / file output streams", e);
        }
    }
    return tempFile;
}

我面临的问题是,当作为 war 文件部署到开发框时 - 应用程序找不到 png 文件。如果我在 Eclipse 中本地运行,这不是问题。

奇怪的是我在资源文件夹中有许多属性文件,如下图所示;

从 jar 文件中加载它们没有问题 - 像这样加载;

public static Properties getDatabaseConnectionProps(ApplicationName appName) throws IOException{

    if(appName == null){
        throw new IllegalArgumentException("Path to proeprties file was null or empty");
    }

    Properties props = null;

    try(InputStream resourceStream = DatabaseUtilities.class.getResourceAsStream("/vimba.properties")) {
        if(resourceStream != null){
            props = new Properties();
            props.load(resourceStream);
            return props;
        }else{
            throw new IllegalArgumentException("In invalid properties file path was provided");
        }
    } catch (IOException e) {
        throw e;
    }
}

那么为什么一种方法可行,而另一种可能不行呢?我完全没有其他选择,所以真的希望有人能拯救这一天

谢谢

【问题讨论】:

  • 您对imagePath 使用的究竟是什么值?对于上面的示例,在一种情况下您使用Class.getResourceAsStream(),在另一种情况下您使用ClassLoader.getResourceAsStream()。在Class 情况下,资源路径必须以斜杠开头,在ClassLoader 情况下,它不得以斜杠开头。
  • 简化方法仍然不起作用 - 我现在使用 is = FileUtilities.class.getResourceAsStream(/EMailBanner); 并遇到异常
  • "doesn't work" 不是对问题的有用描述 - 如果您遇到异常,请向我们展示堆栈跟踪。

标签: java file jar jboss war


【解决方案1】:

我刚刚使用您的代码在本地机器上测试了类似的东西。从我所见,它似乎工作正常。

我能看到的唯一其他问题是 - 如果您检查 JAR(您可以反编译它),请确保您尝试检索的图像在其中并且文件名匹配。

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2014-02-21
    • 2012-09-16
    • 2019-08-24
    • 1970-01-01
    • 2012-08-09
    相关资源
    最近更新 更多