언어(Language)/Java

[Java] 자바 파일 클래스(File Class) 개념 정리 및 활용

잇트루 2022. 9. 28. 04:00
반응형

File

File 클래스는 자바에서 파일 File 클래스를 통해 파일과 디렉토리에 접근할 수 있다.

파일에 접근하기 위해, hello.txt라는 파일을 작성하여 저장한다.

// hello.txt
hello

 

다음은 자바에서 hello.txt 파일에 접근하는 예제이다.

만약, hello.txt 파일이 존재하지 않더라도 컴파일 에러가 발생하지는 않는다.

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

public class FileEx {
    public static void main(String args[]) throws IOException {
        File file = new File("../hello.txt");

        System.out.println(file.getPath());
        System.out.println(file.getParent());
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getCanonicalPath());
        System.out.println(file.canWrite());
    }
}

다음과 같이 File 클래스를 활용하여 작성한 파일에 접근하여 여러 가지 메서드를 활용하여 출력할 수 있다.

 

파일 클래스 메서드 종류

getPath() 메서드

File 클래스를 생성하여 입력한 경로를 반환한다. 만약, 입력한 경로가 상대 경로라면, 상대 경로를 반환한다.

 

getParent() 메서드

File 클래스를 생성하여 입력한 경로의 상위 경로를 반환한다.

 

getAbsolutePath() 메서드

File에 전달한 현재 실행 중인 디렉토리의 절대 경로를 반환한다.

 

getCanonicalPath() 메서드

./와 ../ 같은 경로를 제외한 절대 경로를 반환한다.

 

파일 생성

파일 인스턴스를 생성하는 것이 파일을 생성하는 것은 아니다.

따라서, 파일을 생성하기 위해서는 파일 인스턴스를 생성할 때, 파일 인자에 경로와 파일 이름을 작성하여 createNewFile() 메서드를 호출해야 한다.

File file = new File("./", "fileName.txt");
file.createNewFile();

 

파일 이름 바꾸기

다음은 현재 디렉토리(.)에서 확장자가 .txt인 파일만을 대상으로 파일 이름 앞에 문자열을 붙이는 예제이다.

import java.io.File;

public class FileNameChange {
    public static void main(String[] args) {
        // 현재 경로 File 인스턴스 생성
        File dir = new File("./");

        // 현재 경로에 있는 txt 파일을 File 리스트에 담기
        File[] list = dir.listFiles();

        // 추가할 파일 이름
        String addFileName = "hello";

        for (int i = 0; i < list.length; i++) {
            // File 리스트에 있는 txt 파일 이름 얻기
            String fileName = list[i].getName();

            // 끝 이름이 txt이고, 첫 이름이 hello가 아닌 txt파일 이름 앞에 hello추가
            if (fileName.endsWith("txt") && !fileName.startsWith("hello")) {
                list[i].renameTo(new File(dir, addFileName + fileName));
            }
        }
    }
}
반응형