본문 바로가기

Programing/Java

[JAVA] 비슷한 이름의 특정 파일 모두 지우기

 

자바 프로그램에서 File 삭제 관련 개발을 진행하는 경우가 있을 것이다.

이때 특정 경로에 특정 이름의 파일이 1개만 존재한다면 "디렉토리냐? 파일이냐?" 이 두가지의 경우의 수만 가지고 파일을 쉽게 삭제할 수 있다.

하지만 일반적으로 이미지 파일의 경우 파일의 크기가 큰 원본 파일보다는 Thumnail 이미지로 여러장을 만들어서 저장하는 경우가 있다.
만약 여러장의 Thumnail 이미지를 "A_01, A_02, A_03" 처럼 저장을 해놓을 경우 아래와 같은 방법으로 삭제하도록 한다.

(# 보통 DB에는 Thumnail 이미지의 대표 이름인 "A"만 저장하는 경우가 많다.)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.acma.document;
 
import java.io.File;
 
import org.junit.Test;
import org.springframework.util.ObjectUtils;
 
import lombok.extern.slf4j.Slf4j;
 
 
@Slf4j
public class DeleteFilesWithSimilarNames {
    
    @Test
    public void test() {
        log.info("===========================================================");
        String folderPath = "D:/data/test";
        String fileName = "20190610";
        log.info("Folder Path >>> {}", folderPath);
        log.info("File Name >>> {}", fileName);
        
        boolean isSuccess = deleteOfSimilarNameFile(folderPath, fileName);
        log.info("isSuccess >>> {}", isSuccess);
        log.info("===========================================================");
    }
    
    
    private boolean deleteOfSimilarNameFile(String path, String name) {
        String targetFolderPath = path;
        String targetFileName = name;
        
        // TODO 
        // It is necessary to check whether the parameters have passed to the actual folder and file name.
        
        File folder = new File(targetFolderPath);
        String fileList[] = folder.list();
        
        if(ObjectUtils.isEmpty(fileList)) {
            log.info("{} >>> The file doesn't exist in the directory.", targetFolderPath);
            return false;
        }
        log.info("fileList Length >>> {}", fileList.length);
        
        int failIndex = 0;
        for(String fileName : fileList) {
            if(fileName.contains(targetFileName)) {
                String deleteFilePath = targetFolderPath + File.separator + fileName;
                File deleteFile = new File(deleteFilePath);
                
                if(deleteFile.isDirectory()) {
                    log.info("{} >>> This is a directory.", fileName);
                    continue;
                }
                
                deleteFile.delete();
                
                if(deleteFile.exists()) {
                    failIndex++;
                    log.info("{} >>> Failed to delete file for unknown reason.", fileName);
                    continue;
                }
                
                log.info("{} >>> The file was deleted normally.", fileName);
            }
        }
        
        if(failIndex > 0) {
            log.info("{} file deletions failed for unknown reasons.", failIndex);
            return false;
        }
        
        return true;
    }
}
cs

 

 

 

 

 

 

# 모든 파일이 삭제되었을 경우 성공으로 볼 것인지, 하나의 파일이라도 삭제되었을 경우 성공으로 볼 것인지 등등의 개발 정책에 맞게 소스를 수정해서 사용하면 된다.

'Programing > Java' 카테고리의 다른 글

[Java] 파일 이동  (0) 2019.09.05
[JAVA] 특정 폴더 내 모든 파일 삭제 및 폴더 삭제  (0) 2019.06.21