[Day 8 | Java] File 클래스

y♡ding·2024년 10월 23일
0

데브코스 TIL

목록 보기
45/163

File 클래스는 자바에서 파일이나 디렉토리(폴더)를 조작하기 위해 사용하는 클래스입니다. 파일의 생성, 삭제, 정보 조회와 같은 파일 시스템 관련 작업을 처리할 때 많이 사용됩니다. 하지만, 파일의 내용을 직접 읽거나 쓰는 작업은 하지 않고, 주로 파일이나 디렉토리 자체를 관리하는 데 사용됩니다.

1. File 클래스의 기본 개념

  • 파일디렉토리를 추상화한 클래스입니다.
  • 파일의 존재 여부 확인, 파일 삭제, 파일 경로 정보를 얻는 등의 파일 조작을 할 수 있습니다.
  • 파일뿐만 아니라 디렉토리(폴더)도 조작할 수 있습니다.

2. File 객체 생성

File 클래스는 파일이나 디렉토리의 경로를 기반으로 객체를 생성합니다. 이를 통해 파일에 대한 다양한 작업을 수행할 수 있습니다.

import java.io.File;

public class FileExample {
    public static void main(String[] args) {
        // 파일 객체 생성: 파일의 경로를 전달
        File file = new File("example.txt");

        // 경로 출력
        System.out.println("파일 경로: " + file.getAbsolutePath());
    }
}

3. File 클래스 주요 메서드 및 설명

메서드설명예시
exists()파일 또는 디렉토리가 존재하는지 확인합니다.file.exists()true/false
isFile()경로가 파일인지 확인합니다.file.isFile()true/false
isDirectory()경로가 디렉토리(폴더)인지 확인합니다.file.isDirectory()true/false
getName()파일 또는 디렉토리의 이름을 반환합니다.file.getName()"example.txt"
getAbsolutePath()파일 또는 디렉토리의 절대 경로를 반환합니다.file.getAbsolutePath()"C:/path/to/example.txt"
length()파일의 크기(바이트 단위)를 반환합니다.file.length()1024 (바이트)
createNewFile()새로운 파일을 생성합니다. 이미 파일이 존재하면 생성되지 않습니다.file.createNewFile()true/false
delete()파일 또는 디렉토리를 삭제합니다.file.delete()true/false
mkdir()하나의 디렉토리를 생성합니다.file.mkdir()true/false
mkdirs()필요한 모든 상위 디렉토리까지 포함하여 디렉토리(폴더)를 생성합니다.file.mkdirs()true/false
list()디렉토리 내의 파일 및 디렉토리 이름 목록을 배열로 반환합니다.dir.list(){"file1.txt", "file2.txt", "folder"}
listFiles()디렉토리 내의 파일 및 디렉토리 목록을 File 객체 배열로 반환합니다.dir.listFiles()[File("file1.txt"), File("folder")]
canRead()파일이 읽기 가능한지 확인합니다.file.canRead()true/false
canWrite()파일이 쓰기 가능한지 확인합니다.file.canWrite()true/false

예시코드

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

public class FileExample {
    public static void main(String[] args) {
        try {
            // 파일 객체 생성 (상대경로 또는 절대경로 사용 가능)
            File file = new File("example.txt");

            // 파일이 존재하는지 확인
            if (file.exists()) {
                System.out.println("파일이 존재합니다.");
            } else {
                // 파일이 존재하지 않으면 파일 생성
                if (file.createNewFile()) {
                    System.out.println("새로운 파일이 생성되었습니다.");
                } else {
                    System.out.println("파일을 생성할 수 없습니다.");
                }
            }

            // 파일 이름 확인
            System.out.println("파일 이름: " + file.getName());

            // 파일 절대 경로 확인
            System.out.println("파일 경로: " + file.getAbsolutePath());

            // 파일 크기 (바이트 단위) 확인
            System.out.println("파일 크기: " + file.length() + " 바이트");

            // 파일 읽기 가능 여부 확인
            if (file.canRead()) {
                System.out.println("파일 읽기 가능");
            } else {
                System.out.println("파일 읽기 불가능");
            }

            // 파일 쓰기 가능 여부 확인
            if (file.canWrite()) {
                System.out.println("파일 쓰기 가능");
            } else {
                System.out.println("파일 쓰기 불가능");
            }

            // 파일 삭제 시도
            if (file.delete()) {
                System.out.println("파일이 삭제되었습니다.");
            } else {
                System.out.println("파일을 삭제할 수 없습니다.");
            }

            // 디렉토리 생성
            File dir = new File("myFolder");
            if (dir.mkdir()) {
                System.out.println("디렉토리가 생성되었습니다.");
            } else {
                System.out.println("디렉토리를 생성할 수 없습니다.");
            }

            // 디렉토리 내 파일 목록 출력
            File[] files = dir.listFiles();
            if (files != null) {
                for (File f : files) {
                    System.out.println("디렉토리 안의 파일: " + f.getName());
                }
            } else {
                System.out.println("디렉토리가 비어있거나 존재하지 않습니다.");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.io1;

import java.io.File;

public class FileEx01 {
    public static void main(String[] args) {
        // Directory(특수목적파일) / File

        // 경로
        // 절대 경로 : 드라이브명 부터 추적
        // 상대 경로 : 현재 실행위치 부터 추적

        // 경로를 통한 파일 객체 생성
        **// 1. 디렉토리에 대한 파일 객체 생성**
        File dir =
                new File("/Users/leehayeon/Desktop/java");
        System.out.println(dir);

        **// 2. 파일에 대한 file 객체 생성**
        File file2 = new File("/Users/leehayeon/Desktop/java/test.txt");
        System.out.println(file2);

        File file3 = new File("/Users/leehayeon/Desktop/java", "test.txt");
        System.out.println(file3);

        **// 3. 존재 유무**
        System.out.println(dir.exists());   // true
        System.out.println(file2.exists());  // false
    }
}
        // /Users/leehayeon/Desktop/java/project/LangEx01/src/com/io1

leehayeon@ihayeon-ui-MacBookAir ~ % cd /Users/leehayeon/Desktop/java 
leehayeon@ihayeon-ui-MacBookAir java % mkdir java
leehayeon@ihayeon-ui-MacBookAir java % de java
zsh: command not found: de
leehayeon@ihayeon-ui-MacBookAir java % touch test.txt

터미널 입력 후 결과 값 true로 변경됨 - txt 파일 생성
				**// 3. 존재 유무**
        System.out.println(dir.exists());   // true
        System.out.println(file2.exists());  // true
package com.io1;

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

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

        // 디렉토리
        File file = new File("/Users/leehayeon/Desktop/java/dir1");
        // 디렉토리 생성
        //file.mkdir();  // 결과값 boolean. 존재(생성)하는지 아닌지 여부

        // 디렉토리인지 / 파일인지 구분
        System.out.println(file.isDirectory());   // true
        System.out.println(file.isFile());        // false

        // canExecute() / canRead() / canWrite()
        // isHidden()
        File file2 = new File("/Users/leehayeon/Desktop/java/test.text");
        System.out.println(file2.isHidden());         // 속성을 알 수 있음 (맥에서 속성 확인 "ls -l test.txt")

        // 경로 파악 (디렉)
        System.out.println(file.getName());  // dir1
        System.out.println(file.getParent());  // /Users/leehayeon/Desktop/java
        System.out.println(file.getPath());   // /Users/leehayeon/Desktop/java/dir1

        // 경로 파악 (파일)
        System.out.println(file2.getName());  // test.text
        System.out.println(file2.getParent());  // /Users/leehayeon/Desktop/java
        System.out.println(file2.getPath());   // /Users/leehayeon/Desktop/java/test.text

        // 현재 경로
        File file3 = new File(".");
        System.out.println(file3.getName());  // .
        System.out.println(file3.getParent());   // null
        System.out.println(file3.getPath());  // .

        try {
            System.out.println(file3.getCanonicalPath());   // 상대 경로를 쓰지만 절대 경로로 바꾸고 싶을 때
        } catch (IOException e) {
            throw new RuntimeException(e);   //  /Users/leehayeon/Desktop/java/project/LangEx01
        }
    }
}

// get neame, get path, getCanonicalPath 많이 사용

파일 크기와 수정날짜

package com.io1;

import java.io.File;
import java.util.Date;

public class FileEx03 {
    public static void main(String[] args) {
        File file = new File("/Users/leehayeon/Desktop/java/data.pdf");
        
        // 파일 크기 알아내기
        long fileSize = file.length();
        System.out.println("fileSize = " + fileSize);   // fileSize = 44197859 (byte 단위)

        // byte -> kbyte (1024)
        System.out.println("fileSize = " + fileSize / 1024);  // 43161 (올림 / 내림 등으로 실제 용량과 다르게 출력될 수 있음)

        //----------------------------------------------------

        // 수정 날짜
        long fileDate = file.lastModified();
        System.out.println("fileDate = " + fileDate);  // 1716655643584 (1970년부터 ms로 나옴)

        // 날짜로 바꾸기
        System.out.println(new Date(fileDate).toLocaleString());   // 2024. 5. 26. 오전 1:47:23

    }
}

cd ~/java
ls -l

leehayeon@ihayeon-ui-MacBookAir java % **cd /Users/leehayeon/Desktop/java** 
leehayeon@ihayeon-ui-MacBookAir java % **ls -l**
total 86328
drwxr-xr-x  18 leehayeon  staff       576 10 21 09:43 backup
-rw-r--r--@  1 leehayeon  staff  44197859  5 26 01:47 data.pdf
drwxr-xr-x   2 leehayeon  staff        64 10 23 11:48 dir1
drwxr-xr-x   3 leehayeon  staff        96 10 23 11:48 java
drwxr-xr-x   6 leehayeon  staff       192 10 23 12:23 project
-rw-r--r--   1 leehayeon  staff         0 10 23 11:43 test.txt

drwxr-xr-x : 디렉토리 / -rw-r—r— : 파일

package com.io1;

import java.io.File;

public class FileEx04 {
    public static void main(String[] args) {
        File dir = new File("/Users/leehayeon/Desktop/java");

        // 1. 디렉토리 안 파일 목록 확인 1
        String[] files = dir.list();
        for (String file : files) {
            System.out.println(file);
        }

        // 2. 디렉토리 안 파일 목록 확인 2
        File[] files2 = dir.listFiles();
        for (File file : files2) {
            System.out.println(file.getName());
        }

        // 디렉토리 [] 안에 표시 , 파일 그냥 표시
        File[] files3 = dir.listFiles();
        for (File file : files3) {
            if (file.isDirectory()) {
                //System.out.println("[" + file.getName() + "]");
                System.out.printf("[%s]%n", file.getName());
            } else {
                System.out.println(file.getName());
            }
        } 
    }
}

디렉토리 생성 / 수정 / 삭제 & 파일 생성 / 수정 / 삭제

package com.io1;

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

public class FileEx05 {
    public static void main(String[] args) {
        // 디렉토리 생성 / 이름 변경/삭제
        // mkdir / renameTo / delete

        //File dir = new File("/Users/leehayeon/Desktop/java/dir3");
        //dir.mkdir();             // 생성

        //dir.renameTo(new File("/Users/leehayeon/Desktop/java/dir4"));   // 이름 변경
        //File dir2 = new File("Users/leehayeon/Desktop/java/dir4");      //이름 변경해서 다시 객체 생성
        //dir2.delete();          // 삭제

        // -----------------------------------------------------

        // 파일 생성  / 이름 변경/삭제
        // createNewFile
        try {
            File file = new File ("/Users/leehayeon/Desktop/java/text2.txt");
            file.createNewFile();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

newtest1.txt 파일이 없으면 만들고 있으면 newtest2.txt로 변경

                                                                               
 File file = new File("/Users/leehayeon/Desktop/java/newtest1.txt");           
 if (file.exists()) {                                                          
     file.renameTo(new File("/Users/leehayeon/Desktop/java/newtest2.txt"));    
 } else {                                                                      
     try {                                                                     
         file.createNewFile();                                                 
     } catch (IOException e) {                                                 
         System.out.println(e.getMessage());                                       
     }                                                                         
 }                                                                             

🤷🏻‍♀️ FileWriter는 덮어쓰기 기능인가요?

FileWriter는 기본적으로 파일을 덮어쓰는 방식으로 작동합니다. 즉, 파일이 이미 존재하는 경우, 기존의 내용이 모두 삭제되고 새로운 내용이 파일에 쓰이게 됩니다.
하지만 파일을 덮어쓰지 않고 기존 내용에 추가(append)하려면 FileWriter의 두 번쩨 인자로 true를 전달하여 append모드로 파일을 열 수 있습니다

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterAppendExample {
	public static void main(String[] args) {
    
    try {
    	// FileWriterL append 모드로 파일 열기
        FileWriter writer = new FileWriter("example.txt", true); // 두 번째 매개 변수로 true;
        
        writer.write("추가된 내용.\n");
        writer.close();
        } catch (IOException e) {
        	e.printStackTrace();
        }
    }
}

0개의 댓글

관련 채용 정보