Recent Posts
Recent Comments
Link
06-30 12:53
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

JAVA 운영체제의 경로 방식과 관계 없이 파일 저장 본문

DEV&OPS/Java

JAVA 운영체제의 경로 방식과 관계 없이 파일 저장

ALEPH.GEM 2024. 1. 15. 22:03

 

자바 application에서 파일을 저장할 때 절대경로는 보통 사용하지 않고 상대경로를 사용합니다.

System.property("user.dir")을 통해 현재 application이 실행되는 작업 디렉토리를 얻고 그 기반으로 생성되는 파일의 경로를 지정합니다.

File.separator는 파일 경로를 생성 할 때 운영체제에 맞는 파일의 구분자를 자동으로 선택해 줍니다.

 

public class DynamicFilePathExample {
    public static void main(String[] args) {
        // 현재 작업 디렉토리 확인
        String currentDir = System.getProperty("user.dir");

        // 파일 저장 경로 설정 (현재 작업 디렉토리 내의 example.txt)
        String filePath = currentDir + File.separator + "example.txt";

        // 파일 객체 생성
        File file = new File(filePath);
        FileWriter fw = new FileWriter(file,true);	
        fw.write("파일 내용");
        fw.flush();
        fw.close();

        // 경로 출력
        System.out.println("파일 경로: " + file.getAbsolutePath());
        
        // 이후에는 파일을 해당 경로에 저장하는 로직을 추가할 수 있습니다.
    }
}

 

 

하지만 절대경로가 필요한 경우, System.getProperty("os.name")을 사용하여 운영체제를 확인하여 그에 맞는 경로를 설정해줍니다.

import java.io.File;

public class OSFileExample {
    public static void main(String[] args) {
        // 현재 운영체제 확인
        String os = System.getProperty("os.name").toLowerCase();

        // 파일 저장 경로 설정
        String filePath;
        if (os.contains("win")) {
            // Windows 운영체제인 경우
            filePath = "C:\\MyFiles\\example.txt";
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Unix 또는 MacOS 운영체제인 경우
            filePath = "/home/user/example.txt";
        } else {
            // 기타 운영체제인 경우
            filePath = "/unknown/path/example.txt";
        }

        // 파일 객체 생성
        File file = new File(filePath);

        // 경로 출력
        System.out.println("파일 경로: " + file.getAbsolutePath());
    }
}

 

 

 

 

728x90