Java에서 File 클래스는 파일과 디렉토리 경로명을 추상화한 것이다.
이 클래스를 사용하면 파일이나 디렉토리를 생성, 삭제, 검사할 수 있고, 파일 메타데이터(파일 크기, 수정 날짜 등)를 읽을 수도 있다. File 클래스는 java.io 패키지에 속해 있다.
파일/디렉토리 생성 및 삭제: 파일이나 디렉토리를 생성하거나 삭제할 수 있다.
파일/디렉토리 정보 검색: 파일 이름, 경로, 크기, 수정 날짜와 같은 정보를 얻을 수 있다.
파일/디렉토리 검사: 파일이 존재하는지, 파일인지 디렉토리인지, 읽기/쓰기 가능한지 등을 검사할 수 있다.
디렉토리 내용 읽기: 특정 디렉토리에 있는 파일과 하위 디렉토리 목록을 가져올 수 있다.
File 객체를 생성하는 기본적인 방법은 파일이나 디렉토리의 경로를 문자열로 전달하는 것이다.
File file = new File("경로/파일명.txt");
이 코드는 "경로/파일명.txt"라는 파일에 대한 File 객체를 생성한다. 이 객체를 사용하여 파일의 존재 여부를 확인하거나, 파일 정보를 얻고, 파일을 읽거나 쓸 때 사용할 수 있다.
또한, File 클래스는 파일 입출력에 직접적으로 사용되지는 않지만, 파일의 경로나 이름을 관리하는 데 필요하며, FileInputStream, FileOutputStream, FileReader, FileWriter와 같은 다른 파일 입출력 클래스와 함께 사용된다.
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
// 파일 객체 생성
File myFile = new File("example.txt");
// 파일이 존재하지 않으면 새 파일 생성
if (!myFile.exists()) {
if (myFile.createNewFile()) {
System.out.println("파일 생성 성공!");
} else {
System.out.println("파일 생성 실패.");
}
} else {
System.out.println("파일이 이미 존재합니다.");
}
// 파일의 기본 정보 출력
System.out.println("파일 이름: " + myFile.getName());
System.out.println("절대 경로: " + myFile.getAbsolutePath());
System.out.println("쓰기 가능: " + myFile.canWrite());
System.out.println("읽기 가능: " + myFile.canRead());
System.out.println("파일 크기: " + myFile.length() + "바이트");
} catch (IOException e) {
System.out.println("오류 발생: " + e.getMessage());
}
}
}
이 코드는 "example.txt"라는 이름의 파일을 현재 디렉토리에 생성한다. 파일이 이미 존재하면 존재한다는 메시지를 출력하고, 존재하지 않으면 새로 생성한다. 파일이 성공적으로 생성되거나 이미 존재할 경우, 파일의 이름, 절대 경로, 쓰기/읽기 가능 여부, 파일 크기 등의 정보를 출력한다.
File 클래스와 관련된 예외 처리도 중요하다. 파일 생성 시 IOException이 발생할 수 있으므로 이를 try-catch 블록으로 처리한다. 이렇게 하면 예외가 발생할 경우 사용자에게 오류 메시지를 보여주고 프로그램이 안전하게 종료된다.
package com.mystudy.io1_file;
import java.io.File;
public class FileExam1 {
public static void main(String[] args) {
// File 클래스 사용 예제
// 시스템의 기본 파일 경로 구분자를 가져온다. 윈도우에서는 "\", 유닉스/리눅스에서는 "/" 이다.
String seperator = File.separator;
System.out.println("File.separator : " + seperator);
// 경로 구분자를 char 형태로도 가져올 수 있다.
char seperatorChar = File.separatorChar;
System.out.println("File.separatorChar : " + seperatorChar);
// 시스템의 경로 구분자를 가져옵니다. 이는 환경 변수에서 여러 경로를 구분할 때 사용된다.
// 윈도우에서는 ";", 유닉스/리눅스에서는 ":"이다.
String pathSeparator = File.pathSeparator;
System.out.println("File.pathSeparator : " + pathSeparator);
System.out.println("------------------");
// 시스템의 모든 루트 디렉토리를 조회한다.
File[] listRoots = File.listRoots();
for (File file : listRoots) {
// 각 루트 디렉토리를 출력한다.
System.out.println(file);
}
}
}
File.separator : /
File.separatorChar : /
File.pathSeparator : :
------------------
/
File.separator 사용String separator = File.separator; 이 줄은 시스템의 기본 경로 구분자를 문자열로 가져온다. 예를 들어, 윈도우에서는 \, 유닉스나 리눅스 기반 시스템에서는 /가 된다.File.separatorChar 사용char separatorChar = File.separatorChar; 이 코드는 경로 구분자를 문자(char)로 가져옵니다. 이는 separator와 유사하지만, char 형태로 제공된다.File.pathSeparator 사용String pathSeparator = File.pathSeparator; 이 줄은 시스템의 경로 구분자를 문자열로 가져온다. 이는 환경 변수에서 여러 경로를 구분할 때 사용되는 구분자이다. 예를 들어, 윈도우에서는 ;, 유닉스나 리눅스에서는 :이다.File[] listRoots = File.listRoots(); 이 코드는 시스템의 모든 루트 디렉토리를 File 객체 배열로 반환한다. 그 후 for 루프를 사용하여 이러한 루트 디렉토리들을 출력한다. 이는 시스템의 모든 드라이브 또는 마운트된 파일 시스템의 리스트를 제공할 수 있다.public class FileExam2 {
public static void main(String[] args) {
// File 객체를 생성하고, 파일 및 디렉토리 관련 작업을 수행하는 예제
// 현재 디렉토리에 "temp.txt"라는 이름의 파일을 가리키는 File 객체 생성
// 파일이 실제로 존재하지 않아도 객체 생성 가능
File file1 = new File("temp.txt");
System.out.println("file1: " + file1);
// 현재 디렉토리를 기준으로 한 상대 경로에 있는 파일을 가리키는 File 객체 생성
File file2 = new File(".//file//temp.txt");
System.out.println("file2: " + file2);
// 절대 경로를 사용하여 파일을 가리키는 File 객체 생성
// 이 경로는 루트 디렉토리부터 시작
File file3 = new File("/Users/temp/aaa/temp.txt");
System.out.println("file3: " + file3);
// 각 File 객체의 절대 경로 출력
System.out.println("----- 절대경로명 -----");
System.out.println("file1.getAbsolutePath() : " + file1.getAbsolutePath());
System.out.println("file2.getAbsolutePath() : " + file2.getAbsolutePath());
System.out.println("file3.getAbsolutePath() : " + file3.getAbsolutePath());
// 각 File 객체의 정식 경로명 출력
// '.', '..' 등의 상대 경로 요소를 제거한 경로
System.out.println("---- getCanonicalPath() : 정식경로명(., .. 없앰) ----");
try {
System.out.println("file1.getCanonicalPath() : " + file1.getCanonicalPath());
System.out.println("file2.getCanonicalPath() : " + file2.getCanonicalPath());
System.out.println("file3.getCanonicalPath() : " + file3.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
// 파일이 실제로 존재하는지 확인
System.out.println("---- exists() : 현재 디렉토리에 파일 존재 유무 ----");
System.out.println("file1.exists() : " + file1.exists());
System.out.println("file2.exists() : " + file2.exists());
System.out.println("file3.exists() : " + file3.exists());
// 파일의 속성 정보 출력
System.out.println("---- File 속성정보 ----");
System.out.println("file1.length() : " + file1.length()); // 파일 크기
System.out.println("file1.canRead() : " + file1.canRead()); // 읽기 가능 여부
System.out.println("file1.canWrite() : " + file1.canWrite()); // 쓰기 가능 여부
System.out.println("file1.canExecute() : " + file1.canExecute()); // 실행 가능 여부
// 파일명만 출력
System.out.println("--- getName() : 파일명만 ---");
System.out.println("file1.getName() : " + file1.getName());
System.out.println("file2.getName() : " + file2.getName());
System.out.println("file3.getName() : " + file3.getName());
// 파일이 디렉토리인지, 파일인지 확인
System.out.println("--- isDirectory(), isFile() ---");
System.out.println("file1.isDirectory() : " + file1.isDirectory());
System.out.println("file1.isFile() : " + file1.isFile());
// 파일 삭제 및 디렉토리 생성 예제
System.out.println("============================================");
// "file/temp4.txt" 파일을 삭제, 삭제 성공 여부 반환
File file4 = new File("file/temp4.txt");
System.out.println("file4.delete() : " + file4.delete());
// "temp1/temp2/temp3" 경로에 디렉토리 생성, 중간에 없는 디렉토리도 생성
File file5 = new File("temp1/temp2/temp3");
System.out.println("file5.mkdirs() : " + file5.mkdirs());
}
}
file1: temp.txt
file2: ./file/temp.txt
file3: /Users/temp/aaa/temp.txt
----- 절대경로명 -----
file1.getAbsolutePath() : /Users/sinhuiyeon/eclipse-workspace/20_IO_InputStream_OutputStream/temp.txt
file2.getAbsolutePath() : /Users/sinhuiyeon/eclipse-workspace/20_IO_InputStream_OutputStream/./file/temp.txt
file3.getAbsolutePath() : /Users/temp/aaa/temp.txt
---- getCononicalPath() : 정식경로명(., .. 없앰) ----
file1.getCanonicalPath() : /Users/sinhuiyeon/eclipse-workspace/20_IO_InputStream_OutputStream/temp.txt
file2.getCanonicalPath() : /Users/sinhuiyeon/eclipse-workspace/20_IO_InputStream_OutputStream/file/temp.txt
file3.getCanonicalPath() : /Users/temp/aaa/temp.txt
---- exists() : 현재 디렉토리에 파일 존재 유무 ----
file1.exists() : true
file3.exists() : false
file2.exists() : false
---- File 속성정보 ----
file1.length() : 14
file1.canRead() : true
file1.canWrite() : true
file1.canExecute() : false
--- getName() : 파일명만 ---
file1.getName() : temp.txt
file2.getName() : temp.txt
file3.getName() : temp.txt
--- isDirectory(), isFile() ---
file1.isDirectory() false
file1.isFile() true
============================================
file4.delete() : false
===========
file5.mkdirs() : false
File file1 = new File("temp.txt");: 현재 디렉토리에 "temp.txt"라는 이름의 파일을 가리키는 File 객체를 생성합니다. 파일이 실제로 존재하지 않아도 객체는 생성된다.File file2 = new File(".//file//temp.txt");: 현재 디렉토리를 기준으로 한 상대 경로에 있는 파일을 가리킨다.File file3 = new File("/Users/temp/aaa/temp.txt");: 절대 경로를 사용하여 파일을 가리킨다. 이 경로는 루트 디렉토리부터 시작한다.getAbsolutePath() 메소드를 사용해 각 File 객체의 절대 경로를 출력한다.getCanonicalPath() 메소드는 '.', '..' 등의 상대 경로 요소를 제거한 정식 경로명을 반환한다. 이 메소드는 IOException을 발생시킬 수 있으므로 try-catch 블록으로 감싸져 있다.exists() 메소드를 사용하여 파일이 실제로 존재하는지 확인한다.length() 메소드로 파일 크기를 출력합니다.canRead(), canWrite(), canExecute() 메소드로 파일의 읽기, 쓰기, 실행 가능 여부를 확인한다.getName() 메소드로 각 파일의 이름만 출력한다.isDirectory(), isFile() 메소드로 해당 경로가 디렉토리인지, 파일인지 확인한다.delete() 메소드를 사용해 "file/temp4.txt" 파일을 삭제한다.mkdirs() 메소드를 사용해 "temp1/temp2/temp3" 경로에 여러 개의 디렉토리를 생성한다. mkdirs()는 중간에 없는 디렉토리도 생성해준다.