Path: blob/master/test/jdk/java/nio/file/Files/walkFileTree/MaxDepth.java
41155 views
/*1* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary Unit test for Files.walkFileTree to test maxDepth parameter26* @library ../..27* @compile MaxDepth.java CreateFileTree.java28* @run main MaxDepth29*/3031import java.nio.file.*;32import java.nio.file.attribute.*;33import java.io.IOException;34import java.util.*;3536public class MaxDepth {37public static void main(String[] args) throws IOException {38Path top = CreateFileTree.create();39try {40test(top);41} finally {42TestUtil.removeAll(top);43}44}4546static void test(final Path top) throws IOException {47for (int i=0; i<5; i++) {48Set<FileVisitOption> opts = Collections.emptySet();49final int maxDepth = i;50Files.walkFileTree(top, opts, maxDepth, new SimpleFileVisitor<Path>() {51// compute depth based on relative path to top directory52private int depth(Path file) {53Path rp = file.relativize(top);54return (rp.getFileName().toString().equals("")) ? 0 : rp.getNameCount();55}5657@Override58public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {59int d = depth(dir);60if (d == maxDepth)61throw new RuntimeException("Should not open directories at maxDepth");62if (d > maxDepth)63throw new RuntimeException("Too deep");64return FileVisitResult.CONTINUE;65}6667@Override68public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {69int d = depth(file);70if (d > maxDepth)71throw new RuntimeException("Too deep");72return FileVisitResult.CONTINUE;73}74});75}76}77}787980