Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NIO delete dirs and file

trying NIO and got two problems.1)
create dir files and two inner dirs with file in last dir.

Path pathDir = Path.of("files", "firstDir", "secondDir");
Path pathFile = Path.of("files", "firstDir", "secondDir", "file.txt");
    
Files.createDirectories(pathDir);
Files.createFile(pathFile);

is there any way to combine this into one expression so as not to create folders and files separately?
2) deleting file with dirs

Files.deleteIfExists(pathFile); //delete only file
Files.deleteIfExists(pathDir); // delete only last dir secondDir  

deletes one item at a time, how to delete all folders and a file at once?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I found such an example, but it also deletes only the file

 Files.walk(pathFile)
            .sorted(Comparator.reverseOrder())
            .map(Path::toFile)
            .forEach(File::delete);  

and this option deletes only one file

try {
    Files.walkFileTree(pathFile, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("delete file: " + file.toString());
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            System.out.println("delete dir: " + dir.toString());
            return FileVisitResult.CONTINUE;
        }
    });
} catch (IOException e) {
    e.printStackTrace();
}

>Solution :

To delete directory and file from the root path use the following method:

public static void deleteFilesAndDir(Path pathDir) throws IOException {
        Files.walk(pathDir)
                .sorted(Comparator.reverseOrder())
                .forEach(fileToDelete -> {
                    if (!Files.isDirectory(fileToDelete)) {
                        try {
                            Files.delete(fileToDelete);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (fileToDelete.toFile().getParentFile().length() == 0) {
                            try {
                                FileUtils.deleteDirectory(new File(fileToDelete.toFile().getParent()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    public static boolean deleteDirectory(File directoryToBeDeleted) {
        File[] allContents = directoryToBeDeleted.listFiles();
        if (allContents != null) {
            for (File file : allContents) {
                deleteDirectory(file);
            }
        }
        return directoryToBeDeleted.delete();
    }

Call the above method like below:

deleteDirectory(Path.of("files"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading