【发布时间】: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" 不是对问题的有用描述 - 如果您遇到异常,请向我们展示堆栈跟踪。