SeouliteLab

[Java/자바] 파일 경로 다루기: getPath(), getAbsolutePath(), getCanonicalPath() 메서드 비교 본문

프로그래밍

[Java/자바] 파일 경로 다루기: getPath(), getAbsolutePath(), getCanonicalPath() 메서드 비교

Seoulite Lab 2024. 3. 15. 16:00

Java에서 파일 및 디렉토리의 경로를 다루는 메서드에는 getPath(), getAbsolutePath(), getCanonicalPath()가 있습니다. 이 세 가지 메서드는 각각 파일 또는 디렉토리의 경로를 반환하지만, 그 동작 방식과 반환하는 경로의 형태가 다릅니다. 이 글에서는 이들 메서드의 차이점과 사용법을 살펴보겠습니다.

1. getPath() 메서드

getPath() 메서드는 파일 또는 디렉토리의 상대 경로를 반환합니다. 즉, 현재 작업 디렉토리를 기준으로 한 상대적인 경로를 제공합니다.

import java.io.File;

public class GetPathExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        String path = file.getPath();
        System.out.println("Path: " + path);
    }
}

2. getAbsolutePath() 메서드

getAbsolutePath() 메서드는 파일 또는 디렉토리의 절대 경로를 반환합니다. 절대 경로는 파일 시스템의 루트부터 파일까지의 전체 경로를 나타냅니다.

import java.io.File;

public class GetAbsolutePathExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        String absolutePath = file.getAbsolutePath();
        System.out.println("Absolute Path: " + absolutePath);
    }
}

3. getCanonicalPath() 메서드

getCanonicalPath() 메서드는 파일 또는 디렉토리의 정규화된 절대 경로를 반환합니다. 정규화된 경로는 파일 시스템의 실제 경로를 표현하며, 상대 경로를 절대 경로로 변환하고 심볼릭 링크를 해결합니다.

import java.io.File;
import java.io.IOException;

public class GetCanonicalPathExample {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            String canonicalPath = file.getCanonicalPath();
            System.out.println("Canonical Path: " + canonicalPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}