매번 프로젝트 들어갈때마다 곤란하고 구글링했던 파일 삭제 관련
파일을 삭제하기위한 util class를 호출한다.
1
2
3
4
5
6
|
public int delete(Long orderId) throws Exception{
Path path = Paths.get(디비에서 조회한 파일의 path);
boolean isDeleted = FileStorageUtils.delete(path, 디비에서 조회한 파일의 이름);
return deletCnt;
}
|
cs |
실제 파일 삭제 util class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public static boolean delete(final Path path, final String fileName) throws IOException, DirectoryNotEmptyException { boolean isSuccess = false; Path filePath = path.resolve(fileName); if(Files.notExists(filePath)) { throw new FileNotFoundException("파일을 찾을 수 없습니다."); } isSuccess = Files.deleteIfExists(filePath); // 파일 삭제 if(isDirEmpty(path)) { logger.info("디렉토리가 비어 있습니다. 디렉토리를 삭제 합니다. dir={}", path.toString()); Files.delete(path); // 디렉토리 삭제 } return isSuccess; } public static boolean isDirEmpty(final Path directory) throws IOException { try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) { return !dirStream.iterator().hasNext(); } } | cs |
구글링을 할 수 있지만 귀찮기 때문에 블로그에 메모합니다.
'IT > 개발' 카테고리의 다른 글
JAVA 8 groupingBy, mapping, collectingAndThen (0) | 2021.01.19 |
---|---|
spring junit void test (0) | 2020.12.01 |
spring 파일 다운로드 (0) | 2020.10.28 |
spring 파일 업로드 (0) | 2020.10.27 |
no suitable constructor found for type 에러 분석 (0) | 2020.10.26 |