Reads the given directory non-recursively and returns a map with the names and the streams of all files in this directory. - Java java.nio.file

Java examples for java.nio.file:Path

Description

Reads the given directory non-recursively and returns a map with the names and the streams of all files in this directory.

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main{
    /**//from   w w w .  jav a2s  .  c  o m
     * Reads the given directory non-recursively and returns a map with the names
     * and the streams of all files in this directory. Works also in jar files.
     */
    public static Map<String, InputStream> readDirectory(String path)
            throws IOException {
        Map<String, InputStream> streams = new HashMap<>();
        ClassLoader classLoader = PathUtils.class.getClassLoader();
        ProtectionDomain domain = PathUtils.class.getProtectionDomain();

        // We need to distinguish, if we are in a jar file or not.
        CodeSource codeSource = domain.getCodeSource();
        Path jarFile = Paths.get(codeSource.getLocation().getPath());

        // Check, if we are in jar file.
        if (Files.isRegularFile(jarFile)) {
            final JarFile jar = new JarFile(jarFile.toFile());
            // Fetch all files in the jar.
            final Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                // filter according to the path

                if (name.startsWith(path) && !name.equals(path)) {
                    streams.put(name, classLoader.getResourceAsStream(name));
                }
            }
            jar.close();
        } else {
            // We are not in a jar file.
            File directory = null;
            try {
                // Read the directory.
                directory = new File(classLoader.getResource(path).toURI());
            } catch (Exception e) {
                return streams;
            }

            for (File file : directory.listFiles()) {
                try {
                    streams.put(file.getName(), new FileInputStream(file));
                } catch (Exception e) {
                    continue;
                }
            }
        }
        return streams;
    }
}

Related Tutorials