File이 존재하는지 확인하는 방법을 소개합니다.
File.exists()
File.exists()
는 파일 또는 폴더가 존재하는지 리턴합니다.
만약 폴더가 아닌, 파일이 존재하는지 확인하려면 File.isDirectory()
도 함께 체크해야 합니다.
import java.io.File;
import java.io.IOException;
public class FileExistsExample {
public static void main(String[] args) throws IOException {
File file1 = new File("/home/mjs/tests");
if (file1.exists()) {
if (file1.isDirectory()) {
System.out.println("file1: dir exists");
} else {
System.out.println("file1: file exists");
}
}
File file2 = new File("/home/mjs/tests/test1.txt");
if (file2.exists()) {
if (file2.isDirectory()) {
System.out.println("file2: dir exists");
} else {
System.out.println("file2: file exists");
}
}
}
}
Output:
file1: dir exists
file2: file exists
File.isFile()
File.isFile()
는 파일이 존재하는 경우 true를 리턴합니다. File의 주소가 폴더인 경우는 false를 리턴합니다.
이 API를 사용하면 파일 존재 유무를 체크할 때 File.isDirectory()
를 호출하지 않아도 됩니다.
import java.io.File;
import java.io.IOException;
public class FileExistsExample2 {
public static void main(String[] args) throws IOException {
File file1 = new File("/home/mjs/tests");
if (file1.isFile()) {
System.out.println("file1 exists");
}
File file2 = new File("/home/mjs/tests/test1.txt");
if (file2.isFile()) {
System.out.println("file2 exists");
}
}
}
Output:
file2 exists
Path.toFile()
Path 객체를 이용할 수도 있습니다.
Path.toFile()
은 File을 리턴하고, 위와 동일한 방법으로 확인할 수 있습니다.
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileExistsExample3 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/home/mjs/tests/test1.txt");
if (path.toFile().isFile()) {
System.out.println("file1 exists");
}
File file = path.toFile();
if (file.exists() && !file.isDirectory()) {
System.out.println("file1 exists");
}
}
}
Output:
file1 exists
file1 exists
Loading script...
Related Posts
- Java - hashCode(), 사용하는 이유? 구현 방법?
- Java8의 Stream reduce() 사용 방법 및 예제
- Java - filter, map, flatMap 사용 방법 및 예제
- Java - 2개의 Map 합치기 (merge, putAll)
- Java - ConcurrentModificationException 원인 및 해결 방법
- JUnit - @After와 @AfterClass의 차이점
- JUnit - @Before와 @BeforeClass의 차이점
- java와 javac의 차이점
- Java - 자바(JDK) 버전 확인 방법 (터미널, cmd 명령어)
- Java - java.util.Date를 java.sql.Date로 변환
- Java - 시스템 운영체제(OS) 정보 확인
- Java - 코드 실행 시간 측정
- Java - HashSet.retainAll() 사용 방법 및 예제
- Java - ArrayList.retainAll() 사용 방법 및 예제
- Java - ArrayList를 String으로 변환
- Java - float을 int로 변환
- Java - float을 String으로 변환
- Java - String을 boolean으로 변환
- Java - XML을 JSON으로 변환
- Java - ClassNotFoundException 발생 원인 및 해결 방법
- Java - private 생성자를 사용하는 이유
- Java - non-static method cannot be referenced from a static context
- Java - NoSuchMethodError 원인 및 해결 방법
- Java - Object를 byte[]로 변환
- Java - AbstractMethodError 원인 및 해결
- NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper 에러
- Java - HttpClient에 Timeout 적용
- IntelliJ에서 Java 실행 파일 배포 (Export Runnable JAR)
- Java - JAR 디컴파일 방법 (JD-GUI, JD-CLI)
- Java - 키보드, 마우스 이벤트 받기 (이벤트 후킹)
- Java에서 윈도우 cmd 명령어 실행 및 결과 출력
- Java - Selenium 드라이버 자동 설치 방법
- Java - JSON 라이브러리 사용 방법 (JSONObject, JSONArray)
- Java - ZIP 압축, 압축 해제 (zip, unzip)
- Java - byte[] 배열을 File에 저장