[Java] File 클래스

Hayoung Park·2022년 1월 26일
2

Java

목록 보기
2/2

[java.io.File] File 클래스

File 클래스를 통하여 파일시스템의 파일이나 폴더를 조작할 수 있다.


File 객체 생성

  • 파라미터로 파일이나 디헥토리(폴더)의 경로를 보내 객체를 생성한다.
  • 이 때, 파라미터로 전달되는 경로가 실제로 존재하지 않더라도 생성은 가능하다.
import java.io.File;

public class Main {
  public static void main(String[] args) {
    String filePath = "C:/java/Test.txt";
    String parentPath = "C:/java";
    string fileName = "Test.txt";

    // File(String pathname) 생성자 사용
    File file1 = new File(filePath);

    // File(String parent, String child) 생성자 사용
    File file2 = new File(parentPath, fileName);

    // File(File parent, String child) 생성자 사용
    File parent = new File(parentPath);
    File file3 = new File(parent, fileName);
  }
}

File 클래스의 메서드

  • 소스 코드 실행을 위한 파일/폴더 구성
C:/java (Directory)
C:/java/Test.txt (File)
C:/java/MyDirectory (Directory)

1. 파일/디렉토리 존재 여부 확인 및 기본정보 확인

  • exists() : 존재 여부
  • getName() : 파일명
  • getAbsolutePath() : 절대 경로
  • getPath() : 경로
  • canRead() : 읽기 가능 여부
  • candWrite() : 쓰기 가능 여부
  • canExecute() : 실행 가능 여부
public class Main {
  public static void main(String[] args) {
    String dirPath = "C:/java";

    // File 객체 생성
    File dir = new File(dirPath);

    // 파일명
    System.out.println(dir.getName());  // java

    // 절대 경로
    System.out.println(dir.getAbsolutePath());  // C:/java

    // 경로
    System.out.println(dir.getPath());  // C:/java

    // 존재 여부
    System.out.println(dir.exists());  // ture or false

    // 읽기, 쓰기, 실행 가능 여부
    if(dir.exists()){
      System.out.println(dir.canRead());  // ture or false
      System.out.println(dir.candWrite());  // ture or false
      System.out.println(dir.canExecute());  // ture or false
    }
  }
}

2. 디렉토리 내부에 있는 파일, 디렉토리 출력

  • listFiles() : 내부 파일(디렉토리 포함) 목록을 가져옴. for문으로 순회하며 작업할 수 있음
  • isDirectory() : 경로가 디렉토리인지 검사
  • isFile() : 경로가 파일인지 검사

public class Main {
  public static void main(String[] args) {
    String dirPath = "C:/java";
    File dir = new File(dirPath);

    if(dir.isDirectory()){
      // 파일 목록을 담을 객체
      File[] contents = dir.listFiles();

      for(File file : contents) {
        System.out.println("파일명 : " + file.getName());
        System.out.println("절대 경로 : " + file.getAbsolutePath());
        System.out.println("파일여부 : " + file.isFile());
        System.out.println("------------------------------");
      }
    }
  }
}
// 출력 결과

파일명 : MyDirectory
절대경로 : C:\java\MyDirectory
파일여부 : false
------------------------------
파일명 : Test.txt
절대경로 : C:\java\Test.txt
파일여부 : true
------------------------------

3. 파일 및 디랙토리 생성

  • createNewFile() : 새로운 파일을 생성
  • mkdir() : 새로운 디렉토리를 생성
  • mkdirs() : 상위 디렉토리가 없으면 같이 생성
public class Main {
  public static void main(String[] args) {
    String dirPath = "C:/java";
    File dir = new File(dirPath);

    File newDir = new File(dir, "newDir");  // 생성할 디렉토리

    // 디렉토리 생성
    boolean makeDir = newDir.mkdir();
    System.out.println("디렉토리 생성 결과 : " + makDir); // true

    File newFile = new File(newDir, "newFile");

    // 파일 생성
    try{
      newFile.createNewFile();
    }catch(IOException e){
      e.printStackTrace();
    }

    System.out.println("파일 생성 결과 : " + newFile.exixts()); // true
    System.out.println("새 파일 절대 경로 : " + newFile.getAbsolutePath()); // C:\java\newDir\newFile
  }
}
profile
Faithfulness makes all things possible!

0개의 댓글