java - 如何从war打包的jar中读取PNG

标签 java file jar jboss war

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

我拼凑的代码如下;

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

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

谢谢

最佳答案

我刚刚使用您的代码在本地计算机上测试了类似的内容。从我所看到的来看,它似乎工作得很好。

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

关于java - 如何从war打包的jar中读取PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25058715/

相关文章:

java - 如何修复模块未找到 : spring. web 和类似错误

java - 如何在android中的字符串变量中允许url中存在空格?

javascript - 指定文件上传路径

java - 如何通过 jar 设置主类可执行文件的 vanilla groovy 项目?

java - 从不同的 jar 构建可执行文件

java - MBeans 构造函数与 gradle 依赖项错误

java - 如何在java中制作平滑的模糊效果?

file - Golang 群文件锁定抛出 panic : runtime error: invalid memory address or nil pointer dereference

C++——从二进制文件中读取动态分配的 vector

intellij-idea - Intellij IDEA - JavaFX 打包程序 : access denied