Total Pageviews

2019/11/15

[Java 8] How to delete files in specific directory?

Requirement
How to delete files in specific directory?

How-To
Here has sample code:
package com.xxx.tool.filegenerator.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
@Component
public class FileWriter {

    @Value("${file.property}")
    private String propertyFilePath;

    private void deleteFiles() throws IOException {
        Path path = Paths.get(propertyFilePath);

        try (Stream<Path> walk =  Files.walk(path)){
            walk.map(Path::toFile).forEach(File::delete);
            log.debug("delete existing files from {}", path.toAbsolutePath());
        } catch (IOException e) {
            throw new IOException("Fail to delete existing files : " + e.getMessage(), e);
        }
    }

}


No comments: