gpt4 book ai didi

java - 如何在java中为文档对象设置解析持续时间限制

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:01:20 26 4
gpt4 key购买 nike

我在 java 中使用 Jtidy 解析器。这是我的代码...

  URL url = new URL("www.yahoo.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
Tidy tidy = new Tidy();
Document doc = tidy.parseDOM(in, null);

当我来到这个语句Document doc = tidy.parseDOM(in, null);时,解析页面花费了太多时间,所以我想设置时间限制到document目的。请帮助我,如何设置时间。

最佳答案

您可以使用 java.util.Executors 框架并向其提交限时任务。

下面是一些演示这一点的代码:

// Note that these variables must be declared final to be accessible to task
final InputStream in = conn.getInputStream();
final Tidy tidy = new Tidy();

ExecutorService service = Executors.newSingleThreadExecutor();
// Create an anonymous class that will be submitted to the service and returns your result
Callable<Document> task = new Callable<Document>() {
public Document call() throws Exception {
return tidy.parseDOM(in, null);
}
};
Future<Document> future = service.submit(task);
// Future.get() offers a timed version that may throw a TimeoutException
Document doc = future.get(10, TimeUnit.SECONDS);

关于java - 如何在java中为文档对象设置解析持续时间限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6331154/

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