Loading...

Walking the file tree with Java 7 NIO 2

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

Non-blocking I/O (usually called NIO, and sometimes called “New I/O”) is a collection of Java programming language APIs that offer features for intensive I/O operations.

To walk a file tree, you first need to implement a FileVisitor. A FileVisitor specifies the required behavior at key points in the traversal process: when a file is visited, before a directory is accessed, after a directory is accessed, or when a failure occurs.

See The Java™ Tutorials

Following JUnit test example validates all XML files in a Maven resources directory with the Java built-in SAX (Simple API for XML) API.

/**
 * Validates all the xml docs in `src/main/resources`
 */
public class XmlValdationTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(XmlValdationTest.class);
    private static final String XSD_FILENAME = XSD.getFileName();
    private Set<String> excludeFiles;
    private javax.xml.validation.Validator validator;
    @Before
    public void setUp() throws SAXException {
        // setup file excludes
        setUpExcludes();
        // prepare Validator
        Source xmlFile = new StreamSource(retrieveSchema());
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(xmlFile);
        this.validator = schema.newValidator();
    }
    /** add files to exclude here */
    private void setUpExcludes() {
        this.excludeFiles = new HashSet<String>();
        this.excludeFiles.add("README.md");
    }
    /**
     * retrieve current xsd from artifact xmlschema
     * @return
     */
    private InputStream retrieveSchema() {
        return ClassLoader.getSystemResourceAsStream(XSD_FILENAME);
    }
    @Test
    public void testValidation() throws IOException {
        // arrange - get files
        Path folder = Paths.get("src", "main", "resources", "xml");
        // act
        validate(folder);
    }
    private void validate(Path folder) throws IOException {
        final List<Path> xmlFiles = new ArrayList<>();
        Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".xml") && (!excludeFiles.contains(file.getFileName().toString()))) {
                    xmlFiles.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        for (Path path : xmlFiles) {
            try {
                // act
                this.validator.validate(new StreamSource(path.toFile()));
                LOGGER.info("{} is valid", path.getFileName());
            } catch (SAXException e) {
                // assert
                LOGGER.error("Validation failed for {}", path.getFileName(), e);
                Assert.fail(String.format("%s is NOT valid", path.getFileName()));
            }
        }
    }
}
Please remember the terms for blog comments.