JAVA로 파일 삭제 하기

단비·2023년 5월 8일
0

학습

목록 보기
36/66

File 클래스

  • 파일 내용이 아닌, 파일 자체(껍데기)를 다룸
  • 파일 스트림을 열기 전에 실제 파일에 대한 정보를 확인할 수 있고,
    파일 자체를 삭제하거나 이름을 변경하는 등의 작업을 수행할 수 있음

File 생성자

  • new File(File parent, String child) : 상위 주소와 파일 이름(또는 디렉토리)
  • new File(String pathname) : 상위 주소
  • new File(String parent, String child) : 상위 주소와 파일 이름(또는 디렉토리)
  • new File(URI uri) : 파일의 uri 주소



File 메소드

1. 파일의 정보

리턴값메소드명기능
booleanexists()파일이 실제 존재하는지 판단
booleanisDirectory()디렉토리인지 판단
booleanisFile()파일인지 판단
booleancanRead()파일이 읽기 가능한지 판단
booleancanWrite()파일이 쓰기 가능한지 판단
booleancanExecute()파일이 실행 가능한지 판단
booleanisHidden()파일이 숨김파일인지 판단
intlength()파일의 길이(byte) 반환

2. 파일의 수정

리턴값메소드명기능
booleanrenameTo(File dest)경로가 같으면 이름 변경, 경로가 다르면 이름 바뀌면서 해당 경로로 이동됨
booleandelete()파일 삭제
booleanmkdir()생성자에 넣은 경로에 맞게 폴더 생성
booleancreateNewFile()생성자에 넣은 경로 및 파일명에 맞게 파일 생성

3. 파일의 권한 설정

리턴값메소드명기능
booleansetReadable(treu/false)읽기 권한 설정
booleansetWritable(true/false)쓰기 권한 설정
booleansetExecutable(true/false)실행 권한 설정

4. 파일의 정보 가져오기

리턴값메소드명기능
StringgetPath()파일 또는 디렉토리의 상대 경로 추출 (생성자로 준 경로 반환)
StringgetAbsolutePath()파일 또는 디렉토리의 절대 경로 추출 (생성자 관계없이 절대 경로 반환)
FilegetAbsoluteFile()절대 경로를 가지는 File 객체 생성
StringgetParent()현재 파일의 상위 경로 추출 (생성자에서 제공했을 경우)
FilegetParentFile()현재 파일의 상위 경로를 가진 File 객체 생성 (생성자에서 제공했을 경우)
StringgetName()현재 파일의 이름 추출

5. 파일의 배열 가져오기

리턴값메소드명기능
String[]list()현재 경로의 파일 또는 디렉토리 목록 추출
File[]listFiles()현재 경로의 파일 또는 디렉토리를 가지는 File 타입 배열 추출




파일 삭제

1. Files.delete()

  • 파일 또는 디렉토리를 삭제하기 전에, 해당 파일이 존재하는지 확인해야함
    (삭제 대상이 없으면, NoSuchFileException이 발생)
  • 삭제하려는 대상이 디렉토리이면, 디렉토리는 비어 있어야함
    (디렉토리 안에 파일이 있으면, DirectoryNotEmptyException이 발생)
  • 파일이 열려있거나, JVM 또는 다른 응용프로그램에서 사용중이면
    파일을 삭제하지 못하고 Exception이 발생

2. deleteIfExists()

  • 파일이 존재하는 경우에는 파일을 삭제
    파일이 존재하지 않는 경우에는 false를 리턴
// 1
Files.delete(Paths.get("d:\\example\\file.txt"));
// 2
File[] list = path.listFiles()
list[i].delete();




특정 문자열을 가진 파일의 보관주기 설정하기

Calendar cal = Calendar.getInstance();     // 인스턴스 생성
long todayMil = cal.getTimeInMillis();     // 현재 시간(밀리 세컨드)
long oneDayMil = 24*60*60*1000;            // 일 단위

Calendar fileCal = Calendar.getInstance();
Date fileDate = null;

File path = new File("C:/Users/dbkim/Desktop/TASK/LOG");

// 불러올 리스트의 필터 생성
FilenameFilter filter = logDelete(new FilenameFilter() {
	@Override
	public boolean accept(File dir, String name) {
		return name.contains("AUTH");
	}
});

// 파일 리스트 가져오기
File[] list = path.listFiles(filter);

for(int i=0 ; i < list.length; i++){
	// 파일의 마지막 수정시간 가져오기
	fileDate = new Date(list[i].lastModified());

	// 현재시간과 파일 수정시간 시간차 계산(단위 : 밀리 세컨드)
	fileCal.setTime(fileDate);
	long diffMil = todayMil - fileCal.getTimeInMillis();

	//날짜로 계산
	int diffDay = (int)(diffMil/oneDayMil);

	// 30일이 지난 파일 삭제
	if(diffDay > 30 && list[i].exists()){
		list[i].delete();
	}
}
profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글