소스 내에서 특정 위치에 있는 파일을 읽어야 할 때가 있다.
절대 경로를 써주면 좋긴 하지만, 컴파일해서 배포할 때마다 수정해야 하는 불편함이 있다.
상대 경로로 설정하면 파일의 위치가 변경되지 않는 한 읽을 수 있다.
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를 조회할 수 있다.
해결.!
반응형
'개발 > Java' 카테고리의 다른 글
[Spring] CronSchedule 문법 (0) | 2022.03.18 |
---|---|
[SpringBoot] Debug 실행 오류 (0) | 2022.03.15 |
java.util.LinkedHashMap cannot be cast to object (0) | 2021.07.26 |
Column count doesn't match value count at row 1 (0) | 2021.05.30 |
properties 파일 읽기(read) (0) | 2021.05.30 |
댓글