Java 到主方法的流路径

Java 到主方法的流路径,java,java-8,Java,Java 8,我正在编写一个测试,针对目录中的每个zip文件运行一个类的main方法(它将文件名作为参数)。我有以下资料: private ArrayList<Path> getZipFiles() throws IOException { ArrayList<Path> result = new ArrayList<>(); Path thisDir = Paths.get("src/test/resources"); try (Director

我正在编写一个测试,针对目录中的每个zip文件运行一个类的main方法(它将文件名作为参数)。我有以下资料:

private ArrayList<Path> getZipFiles() throws IOException {
    ArrayList<Path> result = new ArrayList<>();
    Path thisDir = Paths.get("src/test/resources");

    try (DirectoryStream<Path> s = Files.newDirectoryStream(thisDir, "*.zip")){
        s.forEach(filePath -> {
            result.add(filePath);
        });
    }
    return result;
}

@Test
public void test() {
    try {
        ArrayList<Path> p = getZipFiles();
        p.stream().toString().forEach(ValidatorMain::main);
    } catch (IOException e) {
        fail()
    }
}
private ArrayList getZipFiles()引发IOException{
ArrayList结果=新建ArrayList();
Path thisDir=Path.get(“src/test/resources”);
try(DirectoryStream s=Files.newDirectoryStream(thisDir,*.zip))){
s、 forEach(文件路径->{
添加(文件路径);
});
}
返回结果;
}
@试验
公开无效测试(){
试一试{
ArrayList p=getZipFiles();
p、 stream().toString().forEach(ValidatorMain::main);
}捕获(IOE异常){
失败()
}
}

问题是
stream().toString()
不会返回
String[]
。如何以Java-8格式转换/创建字符串[]?

在这种情况下,可以使用
map
方法,如:

 p.stream().map(path -> path.toString()).forEach(ValidatorMain::main);
p.stream().toString()
是一个
对象::toString
调用。它不是
流中的数据处理

要进行正确的检查,您需要:

p.stream().map(Path::toString).allMatch(ValidatorMain::main);

i、 e.检查所有路径是否有效。

如果要使用流API,应重新考虑设计。您不需要将文件收集到
ArrayList
中,然后:

private Stream<Path> getZipFiles() throws IOException {
    Path thisDir = Paths.get("src/test/resources");
    return Files.list(thisDir).filter(p -> p.getFileName().toString().endsWith(".zip"));
}

@Test
public void test() throws IOException {
    try(Stream<Path> s=getZipFiles()) {
        s.map(Object::toString).forEach(ValidatorMain::main);
    }
}

这并不能回答问题,但我不会将
路径
转换为其他任何东西,除非没有其他方法。当然不是字符串,因为
Path
类的全部目的是让您摆脱字符串操纵的恐惧。但它运行的是一个主类,AFAIK只接受string[]args。我使用lambda函数,因为主方法需要string[],而不是string,我不知道如何在流中重铸它。
private List<Path> getZipFiles() throws IOException {
    Path thisDir = Paths.get("src/test/resources");
    return Files.list(thisDir)
        .filter(p -> p.getFileName().toString().endsWith(".zip"))
        .collect(Collectors.toList());
// Alternative:
//    ArrayList<Path> result = new ArrayList<>();
//    try(DirectoryStream<Path> s = Files.newDirectoryStream(thisDir, "*.zip")) {
//        s.forEach(result::add);
//    }
//    return result;
}

@Test
public void test() throws IOException {
    getZipFiles().forEach(p -> ValidatorMain.main(p.toString()));
}