개발일지/Java

Java File

E-room 2022. 9. 24. 17:40
728x90

자바에서는 File 클래스로 파일과 디렉터리에 접근할 수 있다

import java.io.*;

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

        System.out.println(file.getPath());
        System.out.println(file.getParent());
        System.out.println(file.getCanonicalPath());
        System.out.println(file.canWrite());
    }
}
  • getPath : 추상 경로를 문자열로 반환
  • getParent : 상위 경로를 문자열로 반환. 경로 이름이 상위 디렉터리의 이름을 지정하지 않을 경우 null을 반환
  • getCanonicalPath : 절대 경로를 반환
  • canWrite : 파일을 수정할 수 있는지 여부를 boolean으로 반환

 

파일 인스턴스를 생성하는 것이 파일을 생성하는 것은 아님

파일을 생성하기 위해서는 파일 인스턴스를 생성할 때

첫 번째 인자로 경로, 두 번째 인자로 파일명을 작성 후 createNewFile() 메서드를 호출해야 한다.

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

public class Main {
    public static void main(String args[]) throws IOException {
        File file = new File("./", "newEroom.txt");
        file.createNewFile();
    }
}

 

현재 디렉토리에(.) 확장자가 txt인 파일들을 대상으로,

Java로 시작하지 않는 파일들에 Java를 붙여준다

import java.io.File;

public class Main {
    public static void main(String[] args) {

        File parentDir = new File("./");
        File[] list = parentDir.listFiles();

        String prefix = "Java";

        for(int i =0; i <list.length; i++) {
            String fileName = list[i].getName();

            if(fileName.endsWith("txt") && !fileName.startsWith("Java")) {
                list[i].renameTo(new File(parentDir, prefix + fileName));
            }
        }
    }
}

실행 전

 

실행 후

 

공식 문서 참조

https://docs.oracle.com/javase/7/docs/api/java/io/File.html

728x90