当我使用JPL (来自JavaSE 1.8)时,Prolog (SWI-PrologVersion8.2.2)可以返回错误消息而不引发异常。例如,在使用“咨询”时,文件有错误:
import org.jpl7.Query;
public class Test {
public static void main(String[] args) {
try {
String t1 = "consult('test.pl')";
Query q1 = new Query(t1);
q1.hasNext();
} catch (Exception e) {
e.printStackTrace();
}
}
}我在控制台得到输出:
ERROR: test.pl:1:23: Syntax error: Unexpected end of file但也没有例外。因此,我的Java程序无法知道所查询的文件存在错误。我在这个简单示例中使用的文件test.pl只包含一个带有语法错误的简单谓词:
brother(mike, stella)..为了让我的Java程序能够捕捉到这个错误,我能做什么呢?具有类似标题的帖子似乎无法解决这个问题.
也许我可以使用一种句法检查方法,无论是来自JPL,还是其他来源,有什么具体的想法吗?
发布于 2021-09-24 13:49:33
我终于想到要用终端来获取错误或警告信息。我使用Java类来执行swipl.exe,并将所讨论的文件作为参数。需要对输出进行一点处理,但效果很好。下面的代码块演示了解决方案:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestCMD {
public static void main(String[] args) {
try {
String userProjectPath = "Path to the folder of your file, e.g. E:\\";
String userFilename = "Your file name, e.g. test.pl";
Process p = Runtime.getRuntime().exec("\"Path to swipl.exe, e.g. C:\\Program Files\\swipl\\bin\\swipl.exe\" -o /dev/null -c " + userProjectPath + userFilename);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}在我的博客上也给出了这个解决方案。
https://stackoverflow.com/questions/66216361
复制相似问题