PathOperations.java

package org.freshmarker.file;

import org.freshmarker.core.ProcessException;

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

final class PathOperations {

    private PathOperations() {
    }

    @FunctionalInterface
    interface Operation<T> {
        T apply(Path path) throws IOException;
    }

    static <T> T execute(Path path, String operation, Operation<T> function) {
        try {
            return function.apply(path);
        } catch (ProcessException ex) {
            throw ex;
        } catch (IOException | RuntimeException ex) {
            throw new ProcessException("cannot " + operation + " path: " + path, ex);
        }
    }

    static long length(Path path) {
        return execute(path, "read size of", Files::size);
    }

    static long length(File file) {
        return length(file.toPath());
    }

    static long size(Path path) {
        return execute(path, "read size of", value -> {
            try {
                return Files.size(value);
            } catch (NoSuchFileException ex) {
                return 0L;
            }
        });
    }

    static String name(Path path) {
        Path name = path.getFileName();
        return name == null ? "" : name.toString();
    }

    static List<Path> children(Path path) throws IOException {
        try (Stream<Path> children = Files.list(path)) {
            return children.toList();
        }
    }
}