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() 메소드의 경우

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

번호 제목 글쓴이 날짜 조회 수
231 싱글톤 방식의 테스트용 Temporary Data Access Object 황제낙엽 2017.01.12 1603
230 SimpleDateFormat Symbol file 황제낙엽 2016.12.20 74
229 JSON-lib Java Library file 황제낙엽 2013.04.09 91
228 JSP 파일에서 getOutputStream() has already been called for this response 에러 황제낙엽 2013.04.24 11479
227 servlet 에서의 json 한글처리 황제낙엽 2013.04.23 1519
226 -file.encoding의 역할 (다국어, 한국어) 황제낙엽 2013.04.10 235
225 [The type HttpUtils is deprecated] javax.servlet.http.HttpUtils 황제낙엽 2013.03.20 276
224 com.oreilly.servlet.multipart 를 이용한 파일 업로드 file 황제낙엽 2013.03.19 104
223 String to InputSource 황제낙엽 2012.12.03 77
» Class.getResource() vs. ClassLoader.getResource()/getResources() 황제낙엽 2012.06.24 57
221 Jar파일에 포함된 리소스 접근하는 방법(How to read a resource from a JAR file ) file 황제낙엽 2012.06.24 164
220 Java에서 URL 다루기 file 황제낙엽 2012.06.24 88
219 HttpServletResponse.setContentType(java.lang.String type) 과 MIME 타입 황제낙엽 2012.04.20 172
218 code, codebase 속성과 applet object 동적 생성 file 황제낙엽 2012.04.17 85
217 한글 파일명 깨짐으로 살펴본 다국어 처리 문제 (UTF-8) 황제낙엽 2012.03.22 10121
216 BufferedReader.readLine() hangs 황제낙엽 2012.02.23 520
215 OS 쉘 명령어(shell script) 실행하기 [ProcessBuilder, Runtime.getRuntime().exec()] 황제낙엽 2012.02.22 664
214 PreProcess 실행 (전처리기 만들기) file 황제낙엽 2012.01.04 169
213 javax.script와 타입변환 황제낙엽 2012.01.03 62
212 Scripting within Java 황제낙엽 2012.01.03 69