使用 Java 和 JPL 从 SWI-Prolog 检索错误信息

Retrieving ERROR messages from SWI-Prolog using Java and JPL

当我使用 JPL(来自 JavaSE 1.8)时,Prolog(SWI-Prolog 版本 8.2.2)可以 return 一条错误消息而不抛出异常。例如。使用咨询时文件有错误:

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 程序捕捉到这个错误?具有类似标题的 post 似乎无法解决此问题...

也许我可以使用 JPL 或其他来源的语法检查方法,有什么具体的想法吗?

我终于想到尝试使用终端来获取错误或警告消息。我使用 Java 运行时 class 以相关文件作为参数执行 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();
        }
    }
}

我的 blog.

也给出了这个解决方案