gpt4 book ai didi

java - 非法状态异常 : Iterator already obtained

转载 作者:行者123 更新时间:2023-12-02 04:34:46 27 4
gpt4 key购买 nike

所以我写了一个小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);
}
}

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

补充:该错误发生在通过 DirectoryStream 的 foreach 循环处。

最佳答案

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

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

关于java - 非法状态异常 : Iterator already obtained,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30984944/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com