백엔드 (Back-End)/자바 ( JAVA )

[JAVA] .isFile(), .isDirectory(), .exists() Methods

xxvigrufv 2022. 7. 6. 16:13
반응형

java.io.File 주요 메소드이다. 

사용방법 
경로.Methods();

 

boolean exists()     // 파일이 실제 존재하는지 판단
boolean isDirectory()   // 디렉토리인지 판단
boolean isFile()      // 파일인지 판단
boolean canRead()     // 파일이 읽기 가능한지 판단
boolean canWrite()     // 파일이 쓰기 가능한지 판단
boolean canExecute()    // 파일이 실행 가능한지 판단
boolean isHidden()     // 파일이 숨김파일인지 판단
int     length()             // 파일의 길이(byte) 반환
boolean renameTo(File dest)     // 경로가 같으면 이름 변경, 경로가 다르면 이름 바뀌면서 해당 경로로 이동됨
boolean delete()                 // 파일 삭제
boolean mkdir()                 // 생성자에 넣은 경로에 맞게 폴더 생성
boolean createNewFile()   // 생성자에 넣은 경로 및 파일명에 맞게 파일 생성

 

package com.vam.workathome;

import java.io.File;

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

		//Create a file object with the file's address and file name
		File file = new File("C:\Users\SoftCamp\Softcamp\DS\input.txt"); //예시 

		System.out.println(file.exists());      // true
		System.out.println(file.isDirectory()); // false
		System.out.println(file.isFile());      // true
		System.out.println(file.canRead());     // true
		System.out.println(file.canWrite());    // true
		System.out.println(file.canExecute());  // true
		System.out.println(file.isHidden());    // false
		System.out.println(file.length());      // 15
		
		try {
			File dir = new File("C:\\JAVA\\france\\paris\\epel_top");  //예시
			dir.mkdir(); // 폴더 생성

			File txtFile = new File(dir, "input2.txt");
			file.createNewFile(); // 파일 생성

			File txtFile2 = new File("input3.txt");
			file.renameTo(txtFile2); // 경로가 다르므로 파일 이름 변경 및 이동 수행

		} catch (Exception e) {
			System.out.println("File and folder creation failed.");
		}		
	}
}
반응형