sitelink1  
sitelink2  
sitelink3 http://1 
sitelink4 http://ko 
sitelink5 http://devday.tistory.com/570 
sitelink6 http://sitelink1 

Class.getResource() 메소드는 해당 클래스의 소스 파일 위치를 상대 루트로 설정한다.

반면, ClassLoader.getResource()/getResources() 메소드는 클래스패스의 루트를 상대 루트로 설정한다.

다음은 이와 같은 차이를 보여주는 예제이다.

package test;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

public class GetResourceExample {

 public static void main(String[] args) {
  Class<GetResourceExample> clazz = GetResourceExample.class;
  URL resource = clazz.getResource(".");
  System.out.println("resource: " + resource);

  ClassLoader classLoader = clazz.getClassLoader();
  try {
   Enumeration<URL> resources = classLoader.getResources(".");
   System.out.println("resources:");
   while (resources.hasMoreElements()) {
    URL nextElement = resources.nextElement();
    System.out.println(nextElement);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

결과는 다음과 같다.

resource: file:/D:/%ec%9e%91%ec%97%85%ec%8b%a4/Java/JavaExample/bin/test/
resources:
file:/D:/%ec%9e%91%ec%97%85%ec%8b%a4/Java/JavaExample/bin/


Class.getResource() 메소드의 경우

해당 클래스가 포함된 패키지에 따른 디렉토리를 현재 디렉토리로 함을 알 수 있다.

반면, ClassLoader.getResources() 메소드의 경우

클래스패스의 루트를 현재 디렉토리로 함을 확인할 수 있다.

번호 제목 글쓴이 날짜 조회 수
223 String to InputSource 황제낙엽 2012.12.03 601
» Class.getResource() vs. ClassLoader.getResource()/getResources() 황제낙엽 2012.06.24 466
221 Jar파일에 포함된 리소스 접근하는 방법(How to read a resource from a JAR file ) file 황제낙엽 2012.06.24 475
220 Java에서 URL 다루기 file 황제낙엽 2012.06.24 396
219 HttpServletResponse.setContentType(java.lang.String type) 과 MIME 타입 황제낙엽 2012.04.20 509
218 code, codebase 속성과 applet object 동적 생성 file 황제낙엽 2012.04.17 451
217 한글 파일명 깨짐으로 살펴본 다국어 처리 문제 (UTF-8) 황제낙엽 2012.03.22 10403
216 BufferedReader.readLine() hangs 황제낙엽 2012.02.23 809
215 OS 쉘 명령어(shell script) 실행하기 [ProcessBuilder, Runtime.getRuntime().exec()] 황제낙엽 2012.02.22 923
214 PreProcess 실행 (전처리기 만들기) file 황제낙엽 2012.01.04 478
213 javax.script와 타입변환 황제낙엽 2012.01.03 430
212 Scripting within Java 황제낙엽 2012.01.03 393
211 Hex string <-> String object 황제낙엽 2011.11.29 611
210 An alternative to the deep copy technique file 황제낙엽 2011.07.27 570
209 <jsp:include>, include지시자 file 황제낙엽 2011.07.24 438
208 <jsp:include> 액션태그 황제낙엽 2011.07.24 403
207 volatile 에 대한 단상(斷想) 황제낙엽 2011.06.22 425
206 Object element 의 onerror 이벤트 황제낙엽 2011.04.21 295
205 Java 2D Graphics - Reference link 황제낙엽 2011.04.11 459
204 deployJava.js를 이용한 JRE 자동설치 및 Applet 디플로이 file 황제낙엽 2011.04.04 943