0

ковыряю NIO и столкнулся с проблемой, точнее с двумя.
1) создание папки files в корне проекта и две вложенные папки с файлом в последней.

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

    Files.createDirectories(pathDir);
    Files.createFile(pathFile);  

можно это как-нибудь объединить в одно выражение, чтобы не создавать раздельно папки и файлы?

2) удаление папок и файла

    Files.deleteIfExists(pathFile); //удаляет только файл
    Files.deleteIfExists(pathDir); // удаляет только последнюю папку secondDir  

удаляет по одному элементу, как удалить все папки и файл сразу?

нашёл такой пример, но он тоже удаляет только файл

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

и этот вариант удаляет только один файл

    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();
    }

1 ответ 1

1

помогли ребята с ангоязычного сайта.

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

вызываем

  deleteDirectory(Path.of("files").toFile()); 

также можно

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

проблема была в том, что надо передавать не весь путь, а путь к первой папке

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.