mkdir 과 mkdirs()를 이용한 폴더 생성
폴더를 생성하기 위한 함수이며,폴더 생성이 성공할 경우에만 true를 반환한다.
createNewFile()을 이용한 파일 생성
파일 생성이 성공할 경우 true를 반환하며 실패 시 false를 반환한다.
중복된 파일이 존재할 경우 false를 반환하며 생성 작업을 멈춘다.
IOException에 관한 오류 처리를 해야 한다.
파일 경로의 상위 폴더가 없을경우 IOExeption 오류가 발생한다.
delete(),deleteOnExit()을 이용한 폴더 및 파일 삭제
폴더 및 파일의 삭제가 성공할 경우 true를 반환한다.
deleteOnExit()는 자바 프로그램 종료시 삭제 한다.
주로 임시 파일 생성에 사용할 수 있다.
폴더의 경우는 하위 자료가 있을 경우 삭제가 불가능하다.
3.기본 예제
package com.java.io01;
import java.io.File;
import java.io.IOException;
public class File02 {
public static void main(String[] args) {
// 폴더 생성과 파일 생성
// 1.폴더 생성
File file01 = new File("C:\\\\FileTest\\\\dir1");
// 만약 폴더가 없으면 폴더를 생성하시오.
if (file01.exists() == false) {
// file01.mkdir(); 상위 디렉토리가 존재 해야만 생성
file01.mkdirs(); // 상위 디렉토리가 없으면 상위디렉토리를 만들고 생성
}
System.out.println("폴더의 존재 여부 " + file01.exists());
System.out.println("폴더냐?" + file01.isDirectory());
// 2.파일 생성
File file02 = new File("C:\\\\FileTest\\\\dir1\\\\test01.txt"); // 파일 생성 안됨
// 파일이 존재 하는 지 확인 하고 존재하지 않으면 만든다.
// 1)상위 디렉토리를 확인 (경우 따라 상위디렉토리 없이 생성 되는 경우가 있지만,일반적으로 상위
// 디렉토리가 없으면 예외 처리를 해주어야 한다.)
// 상위 디렉토리를 가르키는 File객체를 생성 -->dir
System.out.println(file02.getAbsoluteFile());
System.out.println(file02.getAbsoluteFile().getParentFile());
// 파일의 상위 디렉토리를 담당하는 객체
File dir = file02.getAbsoluteFile().getParentFile(); // 부모 폴더
if (dir.exists() == false) {
dir.mkdirs();
}
// 2)파일 생성
try {
boolean b = file02.createNewFile();
System.out.println("생성여부" + b);
System.out.println("파일의 존재 여부 " + file02.exists());
} catch (IOException e) {
e.printStackTrace();
}
//3.파일 폴더 삭제
//만약에 폴더 하위에 파일이 있을 경우에는 삭제 되지 않는다.
//만일 삭제를 원하면 재귀함수를 이용해서 삭제할 수 있다.
File file03= new File("C:\\\\FileTest\\\\dir2");
file03.delete();
System.out.println("file03존재 여부"+file03.exists());
File file04 = new File("C:\\\\FileTest\\\\dir1\\\\test01.txt");
file04.delete();
System.out.println("file04존재 여부"+file03.exists());
}//main
}