개발 기록이

[JAVA] File, Files 클래스 정리 본문

웹 개발/Back-end

[JAVA] File, Files 클래스 정리

studyingbackhoe 2024. 4. 20. 15:21

1. File 클래스

File 클래스는 파일 및 디렉터리를 생성하고 존재 여부를 확인하는 기능을 제공한다.

File file = new File("test.txt");

 

 

대표적인 메서드를 살펴보자.

 

1) file.createNewFile() : 파일 생성

2) file.mkdir() : 디렉터리 생성

File dir = new File("testDir");
if(dir.mkdir()) {
   System.out.println("디렉토리 생성");
}

 

3) file.exists() : 파일 또는 디렉터리 존재 여부 확인

4) file.getName() : 파일 이름

5) file.getPath() : 파일 경로

6) file.getAbsolutePath() : 파일 절대 경로

7) file.length() : 파일 크기(bytes)

8) file.lastModified() : 파일의 마지막 수정 시간

9) file.delete() : 파일 또는 디렉터리 삭제

 

10) file.renameTo() : 파일 이름 변경

File file = new File("test.txt");
File newFile = new File("newTest.txt");
if (file.renameTo(newFile)) {
    System.out.println("파일 이름 변경");
}

 

11) file.list() : 디렉터리 내 파일 목록 조회

- 파일 및 디렉터리의 이름 조회에 사용됨.

File dir = new File("testDir");
String[] files = dir.list(); //문자열 배열 반환
if (files != null) {
    for (String fileName : files) {
        System.out.println(fileName);
    }
}

 

12) file.listFiles() : 디렉터리 내 파일과 디렉터리 객체 목록 조회

파일 및 디렉터리에 대한 상세 정보를 조회할 수 있다.

File dir = new File("C:/testDir");

// testDir 디렉토리 내의 파일 및 디렉토리에 대한 File 객체 배열을 반환
File[] fileList = dir.listFiles(); 

if (fileList != null) {
    for (File file : fileList) {
        System.out.println("파일명: " + file.getName());
        System.out.println("절대 경로: " + file.getAbsolutePath());
        System.out.println("파일 크기 (bytes): " + file.length());
        System.out.println("마지막 수정 시간: " + file.lastModified());
        if (file.isDirectory()) { // 디렉토리인지 체크
            System.out.println("디렉토리입니다.");
        } else if (file.isFile()) { // 파일인지 체크
            System.out.println("파일입니다.");
        }
    }
}

 

2. Files 클래스

 

Java 7 버전부터 사용이 가능한 클래스이며, Files의 객체는 매개값으로 Path 객체를 받는다.

Paths.get(문자열) 은 문자열을 Path 객체로 변환해준다.

Path beforePath = Paths.get("before.txt"); //복사할 원본 파일 경로
Path afterPath = Paths.get("after.txt"); //복사된 파일의 목적지 경로

 

1) Files.copy(beforePath, afterPath, CopyOption) : 파일 복사

Path beforePath = Paths.get("before.txt"); //복사할 원본 파일 경로
Path afterPath = Paths.get("after.txt"); //복사된 파일의 목적지 경로

Files.copy(beforePath, afterPath, StandardCopyOption.REPLACE_EXISTING);
// StandardCopyOption.REPLACE_EXISTING : 복사된 경로에 이미 파일이 존재하는 경우 덮어쓰기 허용 옵션

 

2) Files.move(beforePath , afterPath , CopyOption) : 파일 이동 및 파일명 변경

Path beforePath = Paths.get("before.txt"); 
Path afterPath = Paths.get("newPath/after.txt");

Files.move(beforePath, afterPath, StandardCopyOption.REPLACE_EXISTING);

 

3) Files.delete(Path) : 파일 삭제

Path deletePath = Paths.get("test.txt"); 
Files.delete(deletePath);

 

4) Files.exists(Path) : 파일 존재 여부 확인

Path path = Paths.get("existingFile.txt");
if (Files.exists(path)) {
	System.out.println("파일이 존재합니다.");
}

 

 

자바 아이콘 제작자: Alfredo Hernandez - Flaticon

출처: OpenAI ChatGPT (https://openai.com), https://rebugs.tistory.com/423