All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.reflections.vfs.SystemDir Maven / Gradle / Ivy

There is a newer version: 1.5.7
Show newest version
package org.reflections.vfs;

import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.Iterator;
import java.util.Stack;
import java.util.List;
import java.io.File;

/*
 * An implementation of {@link org.reflections.vfs.Vfs.Dir} for directory {@link java.io.File}.
 */
public class SystemDir implements Vfs.Dir {
    private final File file;

    public SystemDir(File file) {
        if (file != null && (!file.isDirectory() || !file.canRead())) {
            throw new RuntimeException("cannot use dir " + file);
        }

        this.file = file;
    }

    public String getPath() {
        if (file == null) {
            return "/NO-SUCH-DIRECTORY/";
        }
        return file.getPath().replace("\\", "/");
    }

    public Iterable getFiles() {
        if (file == null || !file.exists()) {
            return Collections.emptyList();
        }
        return new Iterable() {
            public Iterator iterator() {
                return new AbstractIterator() {
                    final Stack stack = new Stack();
                    {stack.addAll(listFiles(file));}

                    protected Vfs.File computeNext() {
                        while (!stack.isEmpty()) {
                            final File file = stack.pop();
                            if (file.isDirectory()) {
                                stack.addAll(listFiles(file));
                            } else {
                                return new SystemFile(SystemDir.this, file);
                            }
                        }

                        return endOfData();
                    }
                };
            }
        };
    }

    private static List listFiles(final File file) {
        File[] files = file.listFiles();

        if (files != null)
            return Lists.newArrayList(files);
        else
            return Lists.newArrayList();
    }

    public void close() {
    }

    @Override
    public String toString() {
        return getPath();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy