SeouliteLab

[Java/자바] 임시 폴더(Temp directory) 경로 가져오기 본문

프로그래밍

[Java/자바] 임시 폴더(Temp directory) 경로 가져오기

Seoulite Lab 2024. 3. 10. 00:53

Java에서는 임시 파일을 생성하거나 작업하는 경우 임시 폴더의 경로가 필요할 수 있습니다. 임시 폴더의 경로를 가져오는 다양한 방법을 살펴보겠습니다.

예제 1: System 클래스를 사용한 방법

public class TempDirectoryExample1 {
    public static void main(String[] args) {
        String tempDir = System.getProperty("java.io.tmpdir");
        System.out.println("Temporary Directory: " + tempDir);
    }
}

System 클래스의 getProperty() 메서드를 사용하여 "java.io.tmpdir" 시스템 속성을 가져와 임시 폴더의 경로를 얻는 방법을 보여줍니다.

예제 2: File 클래스를 사용한 방법

import java.io.File;

public class TempDirectoryExample2 {
    public static void main(String[] args) {
        String tempDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
        System.out.println("Temporary Directory: " + tempDir);
    }
}

File 클래스를 사용하여 시스템 속성을 읽고 임시 폴더의 절대 경로를 가져오는 방법을 보여줍니다.

예제 3: NIO 패키지를 사용한 방법

import java.nio.file.Files;
import java.nio.file.Path;

public class TempDirectoryExample3 {
    public static void main(String[] args) {
        Path tempDir = null;
        try {
            tempDir = Files.createTempDirectory("myTempDir");
            System.out.println("Temporary Directory: " + tempDir.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (tempDir != null) {
                try {
                    Files.deleteIfExists(tempDir);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

NIO(Non-blocking I/O) 패키지를 사용하여 임시 디렉토리를 생성하고 경로를 가져오는 방법을 보여줍니다.