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?
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();
}
CodePudding user response:
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"))
CodePudding user response:
- To create folders and a file you can use this:
Path myRoot = Paths.get("files");
Path pathDir = myRoot
.resolve("firstDir")
.resolve("secondDir");
final boolean created = Files.createDirectories(pathDir)
.resolve("file.txt")
.toFile()
.createNewFile();
- To delete a folder recursively you must start walking from the folder itself
Files.walk(Paths.get("files"))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);