繁体   English   中英

如何在Java中为目录的所有子目录递归运行脚本

[英]How to run script recursively for all the subdirectories of a directory in Java

我正在编写一个 Junit 测试。 我在一个大模块中有几个组件。 我设法修改了一个现有脚本,该脚本现在将扫描一个组件(对路径进行硬编码)并检查测试用例并执行测试。

根目录:模块

子目录列表:

组件 1 组件 2 组件 3 组件 4 组件 5 。 . . . 组件 6

我有以下代码:

@RunWith(Parameterized.class)
public class ContentTest {
    
    private static final Logger log = LoggerFactory.getLogger(ContentTest.class);
    @Parameter
    public String testCase;    
    
    @Parameters( name = "{index}: {0}" )
    public static String[] data() {
        FileSystem fs = FileSystems.getDefault();
        Path p = fs.getPath("Component1/");
        try {
            PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**/*TEST.tab");
            Set<String> tests = 
                    Files.walk(p,FileVisitOption.FOLLOW_LINKS)
            .filter(x -> matcher.matches(x)|| false)
            .map(x -> x.getFileName().toFile().getName())
            .map(x -> x.substring(0, x.length()-4))
            .collect(Collectors.toSet());
            log.info("Going to run the following tests " );
            tests.stream().forEach(log::info);
            String [] result = (String[]) tests.toArray(new String[tests.size()]);
            return result;
        } catch (IOException e) {
            log.error("Could not get testcases." + e);
        }
        return new String[0];
    }
    
    
    @Test
    public void test1() {
        TestCommand tc = new TestCommand();
        tc.setBaseDir(new HdfsResource("Component1/"));
        List<String> args = new ArrayList<>();
        args.add(testCase);
        args.add("--settings");
        tc.run(args.toArray(new String[args.size()]));
    }   


 }

但是,在我的情况下,我对所有组件进行了测试。

现在我的查询是如何以这种方式修改或更改上述脚本。 它将一个接一个地从所有组件执行测试。

任何想法和建议都是有帮助的!!

这可以通过递归方法相当简单地完成,即:


public class MyClass {
    private List<File> directories;

    public static void recurse() {
    
        String[] directories = file.list(new FilenameFilter() {
          @Override
          public boolean accept(File current, String name) {
            return new File(current, name).isDirectory();
          }
        });
        
        for (String dir : directories) {
            File f = new File(dir) {
                if (f.exists()) {
                    this.directories.add(f);
                } else {
                    System.out.println("Directory " + f.getAbsolutePath() + " does not exist");
                }
        }
    }

    public static void main(String[] args) {
        System.out.println("Loop beginning");
        recurse();
        System.out.println("Loop ending");
    }
        

希望这有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM