파일이 "존재"하는지 확인해야 하는 이유는 무엇입니까?
파일 작업(읽기/쓰기/만들기/삭제/업데이트 등)을 처리하는 동안 많은 초보자들은 파일이 존재하는지 확인해야 하는 이유를 궁금해할 수 있습니다. 이에 대한 적절한 응답은 NoSuchFileException을 피하기 위해 항상 파일에 액세스하는 더 안전한 방법입니다. 결과적으로 런타임 예외를 피하기 위해 액세스하기 전에 파일이 존재하는지 확인해야 합니다.
file.exists() 메서드를 사용하여 확인하는 방법은 무엇입니까?
Java 는 주어진 경로에서 관련 파일을 확인하기 위해 매개 변수가 필요하지 않은 간단한 부울 메서드인 file.exists()를 제공합니다. 파일 존재 여부를 확인할 때 3가지 시나리오를 고려하십시오.- 파일을 찾았습니다.
- 파일을 찾을 수 없습니다.
- 권한이 부여되지 않은 경우(보안상의 이유로) 파일 상태를 알 수 없습니다.
예
구현을 확인하기 위해 간단한 코드 예제를 살펴보겠습니다.
package com.java.exists;
import java.io.File;
public class ExistsMethodInJava {
public static void main(String[] args) {
String filePath = "C:\\Users\\Lubaina\\Documents\\myNewTestFile.txt";
File file = new File(filePath);
// check if the file exists at the file path
System.out.println("Does File exists at \"" + filePath + "\"?\t" + file.exists());
filePath = "C:\\Users\\Lubaina\\Documents\\myOtherTestFile.txt";
File nextFile = new File(filePath);
// check if the file exists at the file path
System.out.println("Does File exists at \"" + filePath + "\"?\t" + nextFile.exists());
}
}
산출
파일이 "C:\Users\Lubaina\Documents\myNewTestFile.txt"에 존재합니까? true 파일이 "C:\Users\Lubaina\Documents\myOtherTestFile.txt"에 존재합니까? 거짓
file.exists() 메서드 는 " 디렉토리 " 경로 에도 작동합니다 . 이 방법으로 유효한 디렉토리 경로를 확인하면 true를 반환하고 그렇지 않으면 false를 반환합니다. 더 나은 이해를 위해 다음 코드 블록을 살펴볼 수 있습니다.
package com.java.exists;
import java.io.File;
public class CheckFileExists {
// check if the "file" resource exists and not "directory"
public static boolean checkFileExists(File file) {
return file.exists() && !file.isDirectory();
}
public static void main(String[] args) {
String directoryPath = "C:\\Users\\Lubaina\\Documents\\javaContent";
File direcotry = new File(directoryPath);
// check if the directory exists at the dir path
if (direcotry.exists()) {
System.out.println("Direcotry at \"" + directoryPath + "\" exists.\n");
} else {
System.out.println("Direcotry at \"" + directoryPath + "\" does not exist.\n");
}
// check if the resource present at the path is a "file" not "directory"
boolean check = checkFileExists(direcotry);
System.out.println("Is the resource \"" + direcotry + "\" a File? " + check);
String filePath = "C:\\Users\\Lubaina\\Documents\\myNewTestFile.txt";
File file = new File(filePath);
check = checkFileExists(file);
System.out.println("Is the resource \"" + file + "\" a File? " + check);
}
}
산출
"C:\Users\Lubaina\Documents\javaContent" 디렉토리가 존재합니다. 리소스 "C:\Users\Lubaina\Documents\javaContent"가 파일입니까? false 리소스 "C:\Users\Lubaina\Documents\myNewTestFile.txt"가 파일입니까? 진실
출력에서 볼 수 있듯이 "javaContent"라는 디렉터리는 exists() 메서드 에 의해 유효성이 검사되었습니다 . 따라서 파일이 디렉토리가 아닌지 구체적으로 확인하려면 Java의 File 클래스 에서 제공하는 부울 메소드 isDirectory()를 사용할 수 있습니다.
결론
이 게시물을 마치면 Java에 파일이 있는지 확인하는 방법에 익숙해져야 합니다. 이 기능을 테스트하고 이해하기 위해 자체 프로그램을 작성할 수 있습니다. 익숙해지면 파일의 존재를 확인하는 다른 방법(예: 심볼릭 링크 또는 nio 클래스 사용)도 탐색할 수 있습니다. 행운과 행복한 코딩! :)
더 읽어보기: |
---|
GO TO FULL VERSION