Sunday, November 29, 2015

Java: Two ways to glob

Two ways of globbing.

First, using a DirectoryStream.  This is the better way.

    static List xglob(String filePath, String wc) {
        List result = new ArrayList();

        Path dir = FileSystems.getDefault().getPath(filePath);
        DirectoryStream stream = null;
        try {
            stream = Files.newDirectoryStream(dir, wc);
            for (Path path : stream) {
                result.add(path.getFileName().toString());
            }
            stream.close();

        } catch (IOException e) {
            // glob of something that does not exist is empty
        }
        return result;
    }

Second, using File().

    static List glob2(String dirname_s, String wc) {
        PathMatcher matcher = FileSystems.getDefault()
                                .getPathMatcher("glob:"+wc);
        List result = new ArrayList();

        File dircontents = new File(dirname_s);
        String[] paths = dircontents.list();

        for (String ps : paths) {
            Path p = Paths.get(ps);
            if (matcher.matches(p)) {
                result.add(p.toString());
            }
        }
        Collections.sort(result);
        return result;
    }

blogodex = {"idx" : ["glob", "java"]};

No comments: