WAR 中的 Java getResourceAsStream JAR [英] Java getResourceAsStream JAR inside WAR

查看:39
本文介绍了WAR 中的 Java getResourceAsStream JAR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java webapp WAR 文件,它依赖于它的 WEB-INFlib 目录中的多个 jar.其中一个 JARS 需要通过执行 class.getClassLoader().getResourceAsStream(...) 来加载一些配置文件.但是 InputStream 返回 null.当 JAR 在 WAR 中时,采用这种方法是否有问题?应用部署在Tomcat6上.

I have a Java webapp WAR file that depends on multiple jars in it's WEB-INFlib directory. One of these JARS needs to load some config files by doing class.getClassLoader().getResourceAsStream(...). However the InputStream resturns null. Is there a problem with taking this approach when the JAR is inside a WAR? The app is deployed on Tomcat6.

编辑更多信息:

我正在尝试从文件加载 SQL 查询,以便我可以运行它们.它们位于 Web 应用程序的 WAR 中的单独 DAO jar 中,位于 WEB-INF/lib

I'm tring to load in SQL queries from files so I can run them. These are located in a separate DAO jar within the web app's WAR, under WEB-INF/lib

mywebapp.war
        -- WEB-INF
          -- lib
             -- mydao.jar
               ---- com/companyname/queries
                   -- query1.sql
                   -- query2.sql
                   -- query3.sql
                   ...

用于加载类的代码

public class QueryLoader {

 private static final Logger LOGGER = Logger.getLogger(QueryLoader.class.getName());

public String loadQuery(String fileName) {
  final String newline = "
";

  BufferedReader reader = new BufferedReader(new InputStreamReader(         
        QueryLoader.class.getClassLoader().getResourceAsStream(
              "/com/companyname/queries/" + fileName)));
  StringBuilder sb = new StringBuilder();
  String line;
  try {
     while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append(newline);
     }
  } catch (IOException e) {
     LOGGER.error(e);
  }

我也尝试将 getResourceAsStream 行更改为

I have also tried changing the getResourceAsStream line to

Thread.currentThread().getContextClassLoader().getResourceAsStream(

没有成功.

我的开发环境是 MS Windows Vista,但在此环境和 Ubuntu 上运行时遇到相同的错误.

My development environment is MS Windows Vista and but I encounter the same error when running it on this environment and on Ubuntu.

推荐答案

设法通过使用 Spring 的资源加载器来使其工作

Managed to get it to work by using Spring's resource loader instead

public String loadQuery(String fileName) {
  final String newline = "
";

  ApplicationContext ctx = new ClassPathXmlApplicationContext();
  Resource res = ctx.getResource("classpath:/com/msi/queries/" + fileName);
  BufferedReader reader;
  StringBuilder sb = new StringBuilder();
  try {
     reader = new BufferedReader(new InputStreamReader(res.getInputStream()));
     String line;

     while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append(newline);
     }
  } catch (IOException e) {
     LOGGER.error(e);
  }

  return sb.toString();

}

这篇关于WAR 中的 Java getResourceAsStream JAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆