我正在尝试编写一些代码,允许我访问一个文件(特别是 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 中本地运行,这不是问题。
奇怪的是,我在资源文件夹中有许多属性文件,如下图所示;
我从 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/