본문 바로가기
개발/Java

JAVA(자바) ClassPath(클래스패스) 가져오기

by 용술이 2021. 5. 30.

소스 내에서 특정 위치에 있는 파일을 읽어야 할 때가 있다. 

절대 경로를 써주면 좋긴 하지만, 컴파일해서 배포할 때마다 수정해야 하는 불편함이 있다. 

 

상대 경로로 설정하면 파일의 위치가 변경되지 않는 한 읽을 수 있다.

 

webapp의 파일들인 경우 컴파일을 해도 파일의 위치가 변경되지 않으니 쉽게 경로를 쓸 수 있지만

java class의 경우 컴파일이 되면 설정된 위치에 생성되기 때문에 경로를 찾기 쉽지 않다. 

 

그래서 class 가 생성되는 경로인 class Path를 가져오는 방법을 알아보자

 

1. System.getProperty 이용하여 jar 파일을 가져올 수 있다.

1
2
3
4
5
6
7
8
    @Test
    public void getClassPath() {
        String sPath = System.getProperty("java.class.path");
        String[] classpathEntries = sPath.split(File.pathSeparator);
        for (String path : classpathEntries) {
            System.out.println(path);
        }
    }
cs

[결과]

          .
          .
          .
          .
          .
D:\util\java1.8.0\jre\lib\charsets.jar
D:\util\java1.8.0\jre\lib\ext\access-bridge-32.jar
D:\util\java1.8.0\jre\lib\ext\access-bridge.jar
D:\util\java1.8.0\jre\lib\ext\cldrdata.jar
D:\util\java1.8.0\jre\lib\ext\dnsns.jar
          .
          .
          .
          .
          .

 

2. File을 이용하여 디렉터리 찾기 

1
2
3
4
5
6
    @Test
    public void getClassPath2() {
        String sPath = sPath = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getAbsolutePath();
 
        System.out.println(sPath);
    }
cs

[결과]

D:\cloudmashbatch\target\test-classes

 

 

여러 가지 방법이 많지만, 일단 이 두 가지로 웬만한 class path를 조회할 수 있다.

 

해결.! 

 

반응형

댓글