IllegalStateException:迭代器已经获得

时间:2015-06-22 16:17:03

标签: java file loops path

所以我写了一个小Java程序来测试我用各种测试文件制作的一些堆栈语言,但由于某种原因它不起作用。 这是代码:

import org.apache.commons.io.FilenameUtils;
import java.io.IOException;
import java.nio.file.*;

public class Main {

public static void run(DirectoryStream<Path> files) throws IOException {
    for (Path f : files) {
        String ext = FilenameUtils.getExtension(f.toString());
        if (ext.equals("slang")) {               // if extension "slang" run program slang with slang test file as argument and dump result int a file with the same base name but .test extension
            Runtime.getRuntime().exec("java slang < " + f.getFileName() + " > " + FilenameUtils.getBaseName(f.toString()) + ".test");
        }
    }
}

public static void main(String[] args) {
    try {
        Runtime.getRuntime().exec("javac slang.java; ");         // compile slang
    } catch (IOException e) {
        e.printStackTrace();
    }
    Path dir = Paths.get("C:\\Users\\Anton\\Documents\\TU Wien\\PK\\SS2015\\Abschlussaufgabe\\Slang\\progs");
    try { //create list of all Files in test directory Files
        DirectoryStream<Path> files = Files.newDirectoryStream(dir);
        run(files);                                             //run all needed files
        compare(files);                                         //compare all files
    } catch (IOException | DirectoryIteratorException x) {
        System.err.println(x);
        x.printStackTrace();
    }
}


public static void compare(DirectoryStream<Path> files) throws IOException {
    for (Path f : files) {
        String ext = FilenameUtils.getExtension(f.toString());                  //is it a test file?
        if (ext.equals("test")) {
            String outputPath = FilenameUtils.getBaseName(f.toString()) + ".output";       //get path of output
            Path output = Paths.get(outputPath);
            if (!fileEquals(f, output)) {                                   // compare them
                System.err.println("Not Equal:" + f.getFileName());         // errormessage if fault, else just continue
            }
        }
        //files.iterator().remove();
        //files.iterator().next();
    }
}

private static boolean fileEquals(Path p, Path q) throws IOException {
    String contentP = new String(Files.readAllBytes(p));                    //turn into string then compare, no idea whether best practice
    String contentQ = new String(Files.readAllBytes(q));
    return contentP.equals(contentQ);
}
}

当我运行它时,它抛出“线程中的异常”主“java.lang.IllegalStateException:Iterator已经获得”。 我已经尝试使用iterator()。remove和iterator()。next,但它只会导致应用程序在抛出错误之前运行更长时间。 感谢您事先获得任何帮助。

添加:通过DirectoryStream在foreach循环中发生错误。

1 个答案:

答案 0 :(得分:2)

每次迭代文件时都必须调用DirectoryStream<Path> files = Files.newDirectoryStream(dir);

请检查这个问题...... java.lang.IllegalStateException: Iterator already obtained