어제 오늘 내일

[Java] 파일, 디렉토리 존재 여부 확인하기 본문

IT/Java

[Java] 파일, 디렉토리 존재 여부 확인하기

hi.anna 2021. 5. 29. 17:35

 

Java API를 이용하여 파일을 다루는 방법을 알아보고 있습니다.

[Java] 텍스트 파일 읽기 ( FileReader, BufferedReader, Scanner, Files )

[Java] 파일 생성하는 3가지 방법 (File, FileOutputStream, Files)

 

이번에는 특정 파일이나, 디렉토리가 존재하는지 체크하는 방법을 알아보도록 하겠습니다.

  1. java.io.File
  2. java.nio.file.Files

 

 

1. java.io.File

public boolean exists()

주어진 파일이나 디렉토리가 존재하는지 여부를 리턴합니다.

 

public boolean isDirectory()

주어진 File 객체가 디렉토리일 경우 true를 리턴합니다.

 

public boolean isFile()

주어진 File 객체가 디렉토리가 아니고 normal file일 경우 true를 리턴합니다.

 

  예제 코드  

import java.io.File;

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

        File file = new File("d:\\example\\file.txt");

        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("디렉토리가 존재합니다");
            } else if (file.isFile()) {
                System.out.println("파일이 존재합니다");
            }
        } else {
            System.out.println("파일이나 디렉토리가 존재하지 않습니다");
        }
    }
}

file.exists()

주어진 파일 또는 디렉토리가 존재하는지 체크합니다.

 

file.isDirectory()

file.isFile()

주어진 파일이 디렉토리인지, 파일인지 체크합니다.

 

 

 

2. java.nio.file.Files

public static boolean exists​(Path path, LinkOption... options)

파라미터로 주어진 path의 파일이 존재하는지 여부를 체크합니다.

두번째 파라미터인 LinkOption은 symbolic link 파일의 target 파일이 존재하는지 여부에 따라서

true/false를 리턴합니다.

LinkOption을 파라미터로 전달하지 않으면,

default로, symbolic link의 target이 존재하지 않으면 false, 존재하면 true를 리턴합니다.

 

public static boolean isDirectory​(Path path, LinkOption... options)

파라미터로 주어진 Path가 디렉토리인지 여부를 체크합니다.

LinkOption을 파라미터로 전달하지 않으면,

default로, symbolic link가 가리키는 대상이, 디렉토리인지 체크합니다.

 

public static boolean isRegularFile​(Path path, LinkOption... options)

파라미터로 주어진 Path가 디렉토리가 아닌 파일인지 체크합니다.

LinkOption을 파라미터로 전달하지 않으면,

default로, symbolic link가 가리키는 대상이, 파일인지 체크합니다.

 

 

  예제 코드  

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

        Path path = Paths.get("d:\\exampleㄹ\\");

        if (Files.exists(path)) {
            if (Files.isDirectory(path)) {
                System.out.println("디렉토리가 존재합니다");
            } else if (Files.isRegularFile(path)) {
                System.out.println("파일이 존재합니다");
            }
        } else {
            System.out.println("파일이나 디렉토리가 존재하지 않습니다");
        }
    }
}

Files.exists(path)

파라미터로 전달된 Path 객체가 가리키는 디렉토리 또는 파일이 존재하는지 체크합니다.

 

Files.isDirectory(path)

Files.isRegularFile(path)

Path 객체가 가리키는 대상이 디렉토리인지 파일인지 체크합니다.

 


 

Java API를 이용하여, 파일 또는 디렉토리가 존재하는지 체크하는 방법을 알아보았습니다.

 

 

반응형
Comments