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);
  }
}
C:/java (Directory)
C:/java/Test.txt (File)
C:/java/MyDirectory (Directory)
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
    }
  }
}
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
------------------------------
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
  }
}