상대경로 찾기

moon.kick·2025년 3월 5일

Java에서 상대경로 찾기

Java에서 파일을 읽을 때 상대경로를 설정하는 방식은 여러 가지가 있습니다. PropertiesExam 클래스가 실행되는 위치와, a.properties 파일이 어디에 위치해 있는지에 따라 경로 설정이 달라질 수 있습니다.


1. 상대경로란?

  • 절대경로: /Users/username/project/src/ex0305/map/a.properties
    • 시스템에 종속적이며, 프로젝트가 이동하면 깨질 가능성이 있음.
  • 상대경로: src/ex0305/map/a.properties
    • 실행되는 클래스의 위치를 기준으로 탐색.

2. 상대경로 설정 방법

다음과 같은 네 가지 방법이 있습니다.

방법 1: 프로젝트 src 폴더를 기준으로 접근 (절대경로 X)

InputStream inputStream = new FileInputStream("src/ex0305/map/a.properties");
pro.load(inputStream);

✔️ 주의: FileInputStream을 사용할 경우 src/부터 시작하는 경로를 써야 하지만, 이 방법은 실행 환경에 따라 다르게 동작할 수 있어 권장되지 않음.


방법 2: 현재 클래스가 위치한 패키지 내에서 파일 로딩

InputStream inputStream = PropertiesExam.class.getResourceAsStream("a.properties");
pro.load(inputStream);

✔️ getResourceAsStream("파일명")은 현재 클래스와 같은 패키지에 있는 파일을 불러올 때 사용.
✔️ a.properties 파일이 ex0305/map/ 폴더 내에 존재해야 함.


방법 3: this.getClass() 사용 (현재 클래스 기준)

InputStream inputStream = this.getClass().getResourceAsStream("a.properties");
pro.load(inputStream);

✔️ getResourceAsStream("파일명")을 사용하면 현재 클래스가 위치한 패키지를 기준으로 파일을 찾음.


방법 4: ClassLoader 사용 (resources 폴더에서 파일 읽기)

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ex0305/map/a.properties");
pro.load(inputStream);

✔️ getClassLoader().getResourceAsStream()을 사용하면 resources 폴더에 있는 파일도 읽을 수 있음.
✔️ 프로젝트 구조가 아래와 같다면 src/ 없이 ex0305/map/a.properties처럼 지정해야 함.

📂 프로젝트 구조 예시:

/project-root
  ├── src
  │     ├── ex0305
  │     │    ├── map
  │     │    │    ├── PropertiesExam.java
  │     │    │    ├── a.properties
  ├── target (빌드 결과)
  ├── resources
  │     ├── config.properties

✔️ 만약 resources 폴더 안에 a.properties가 있다면:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("a.properties");

이렇게 사용해야 함.


3. 실행 환경에서 상대경로 확인 방법

현재 Java 프로그램이 실행되는 경로를 확인하려면 아래 코드를 사용:

System.out.println("현재 디렉토리: " + System.getProperty("user.dir"));

이 코드를 실행하면 프로젝트의 루트 디렉토리가 출력됨.
이를 기준으로 상대경로를 설정하면 됨.


4. 상대경로 문제 해결 방법

  1. 파일이 있는 위치 확인

    File file = new File("src/ex0305/map/a.properties");
    System.out.println("파일 경로: " + file.getAbsolutePath());
    System.out.println("파일 존재 여부: " + file.exists());
    • 실행해서 파일 존재 여부: false가 나오면 경로가 잘못된 것.
  2. 경로 문제 해결 방법

    • a.propertiessrc/ex0305/map/에 있다면:
      InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ex0305/map/a.properties");
    • a.propertiesresources/ 폴더에 있다면:
      InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("a.properties");

5. 결론

  • FileInputStream을 사용하면 src/ 기준으로 작성하지만, 권장되지 않음.
  • 클래스가 위치한 패키지 안에서 파일을 찾으려면 getResourceAsStream() 사용.
  • ClassLoader를 사용하면 resources 폴더 내 파일도 읽을 수 있음.
  • System.getProperty("user.dir")를 출력하여 현재 실행 경로를 확인하고 상대경로를 조정.

이제 상대경로를 제대로 설정할 수 있을 거예요! 😊

profile
@mgkick

0개의 댓글