如何从战争中打包的罐子中读取PNG

时间:2014-07-31 12:20:14

标签: java file jar jboss war

我正在尝试编写一些代码,允许我访问一个文件(特别是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中本地运行它不是问题。

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

enter image description here

我在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;
    }
}

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

由于

1 个答案:

答案 0 :(得分:0)

我刚刚使用您的代码在本地计算机上测试过类似的东西。从我能看到的情况来看似乎工作正常。

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

相关问题