UFO ET IT

this.getClass (). getClassLoader (). getResource (“…”) 및 NullPointerException

ufoet 2021. 1. 5. 08:24
반응형

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());

  }

하지만 코드를 junit 4 단위 테스트로 실행하면 NullPointerException이 발생합니다. 이것은 전에 수백만 번 잘 작동했습니다. 어떤 아이디어?

이 가이드를 따랐습니다.

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

그러나 여전히 동일한 오류가 발생합니다.


사용할 때

this.getClass().getResource("myFile.ext")

getResource패키지와 관련된 리소스를 찾으려고합니다. 사용하는 경우 :

this.getClass().getResource("/myFile.ext")

getResource 절대 경로로 취급하고 완료 한 경우처럼 클래스 로더를 호출합니다.

this.getClass().getClassLoader().getResource("myFile.ext")

경로에 선행 /사용할 수없는 이유 ClassLoader는 모든 ClassLoader경로가 절대적이므로 경로 /에서 유효한 첫 번째 문자 가 아니기 때문 입니다.


툴,

  • 사용할 때 .getClass().getResource(fileName)fileName의 위치가 호출 클래스의 위치와 동일한 것으로 간주합니다.
  • 사용할 때 .getClass().getClassLoader().getResource(fileName)fileName의 위치가 루트, 즉 bin폴더 라고 간주 합니다.

출처 :

package Sound;
public class ResourceTest {
    public static void main(String[] args) {
        String fileName = "Kalimba.mp3";
        System.out.println(fileName);
        System.out.println(new ResourceTest().getClass().getResource(fileName));
        System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
    }
}

출력 :

Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3

그것은해야한다 getResource("/install.xml");

자원 이름은 테스트 인 경우 getClass () 클래스 상주, 예를 들면 어디를 기준으로 org/example/foo/MyTest.class다음 getResource("install.xml")에 볼 것이다 org/example/foo/install.xml.

당신이 경우 install.xmlsrc/test/resources, 그것은 따라서 당신이 가진 자원 이름을 씁니다, 클래스 패스의 루트입니다 /.

또한 가끔 만 작동한다면 Eclipse가 출력 디렉토리 (예 :)를 정리 target/test-classes했고 리소스가 런타임 클래스 경로에서 단순히 누락 되었기 때문일 수 있습니다 . 패키지 탐색기 대신 Eclipse의 네비게이터보기를 사용하는지 확인하십시오. 파일이 없으면 mvn package목표를 실행하십시오 .


다음 조건에서 동일한 문제가 발생했습니다.

  • 리소스 파일은 Java 소스 폴더 ( src/test/java) 의 Java 소스 파일과 동일한 패키지에 있습니다.
  • 명령 줄에서 maven을 사용하여 프로젝트를 빌드하고 NullPointerException.
  • 명령 줄 빌드가 리소스 파일을 test-classes폴더에 복사하지 않아 빌드 실패를 설명했습니다.
  • When going to eclipse after the command line build and rerun the tests in eclipse I also got the NullPointerException in eclipse.
  • When I cleaned the project (deleted the content of the target folder) and rebuild the project in Eclipse the test did run correctly. This explains why it runs when you start with a clean project.

I fixed this by placing the resource files in the resources folder in test: src/test/resources using the same package structure as the source class.

BTW I used getClass().getResource(...)


When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.


I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.

For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"

I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.

<build>
    <defaultGoal>package</defaultGoal>
    <directory>${basedir}/build</directory>
<build>

I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"

I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.


I had the same issue working on a project with Maven. Here how I fixed it: I just put the sources (images, musics and other stuffs) in the resources directory:

src/main/resources

I created the same structure for the packages in the resources directory too. For example:

If my class is on

com.package1.main

In the resources directory I put one package with the same name

com.package1.main

So I use

getClass().getResource("resource.png");

One other thing to look at that solved it for me :

In an Eclipse / Maven project, I had Java classes in src/test/java in which I was using the this.getClass().getResource("someFile.ext"); pattern to look for resources in src/test/resources where the resource file was in the same package location in the resources source folder as the test class was in the the test source folder. It still failed to locate them.

Right click on the src/test/resources source folder, Build Path, then "configure inclusion / exclusion filters"; I added a new inclusion filter of **/*.ext to make sure my files weren't getting scrubbed; my tests now can find their resource files.

ReferenceURL : https://stackoverflow.com/questions/3803326/this-getclass-getclassloader-getresource-and-nullpointerexception

반응형