相关疑难解决方法(0)

this.getClass().getClassLoader().getResource("...")和NullPointerException

我在eclipse helios中创建了一个带有单个子模块的最小maven项目.

在src/test/resources文件夹中,我放了一个文件"install.xml".在文件夹src/test/java中,我创建了一个包含单个类的包:

  @Test
  public void doit() throws Exception {
    URL url = this.getClass().getClassLoader().getResource("install.xml");
    System.out.println(url.getPath());

  }
Run Code Online (Sandbox Code Playgroud)

但是当我将代码作为junit 4单元测试运行时,我只得到一个NullPointerException.这之前已经运行了数百万次.有任何想法吗?

我遵循了这个指南:

http://www.fuyun.org/2009/11/how-to-read-input-files-in-maven-junit/

但仍然得到相同的错误.

eclipse maven-2 classloader

57
推荐指数
5
解决办法
17万
查看次数

如何从资源文件夹中获取文件.Spring框架

我正在尝试解组我的xml文件:

public Object convertFromXMLToObject(String xmlfile) throws IOException {
    FileInputStream is = null;
    File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
    try {
        is = new FileInputStream(file);
        return getUnmarshaller().unmarshal(new StreamSource(is));
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:java.io.FileNotFoundException:null(没有这样的文件或目录)

这是我的结构:

在此输入图像描述

为什么我无法从资源文件夹中获取文件?谢谢.

更新.

重构后,

URL url = this.getClass().getResource("/ xmlToParse/companies.xml"); 文件文件=新文件(url.getPath());

我可以更清楚地看到错误:

java.io.FileNotFoundException:/content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml(没有这样的文件或目录)

它试图找到WEB-INF/classes /我在那里添加了文件夹,但仍然收到此错误:(

在此输入图像描述

java spring-mvc fileinputstream java-io

19
推荐指数
3
解决办法
6万
查看次数