Java 如何从包装在战争中的罐子中读取PNG
我正在尝试编写一些代码,允许我访问一个文件,特别是EMailBanner.png,它被包装成一个jar,然后包含在war中 我拼凑的代码如下:Java 如何从包装在战争中的罐子中读取PNG,java,file,jar,jboss,war,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"); }
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中本地运行,这不是问题
奇怪的是,我在resources文件夹中有许多属性文件,如下图所示
我从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,您可以对其进行反编译,请确保您尝试检索的图像在其中,并且文件名匹配。您使用的imagePath值到底是多少?在上面的示例中,一种情况下使用Class.getResourceAsStream,另一种情况下使用ClassLoader.getResourceAsStream。在类的情况下,资源路径必须以斜杠开始,在类加载器的情况下,它不能以斜杠开始。简化方法仍然不起作用-我现在使用的是is=FileUtilities.Class.getResourceAsStream/EMailBanner;我得到一个异常Doesn't work不是对问题的一个有用的描述-如果你得到一个异常,那么向我们展示堆栈跟踪。