Java中的phantomjs在process.waitFor()中被阻止
在Java中使用phantomJs的一个简单示例将无限制地阻止:Java中的phantomjs在process.waitFor()中被阻止,java,phantomjs,Java,Phantomjs,在Java中使用phantomJs的一个简单示例将无限制地阻止: public void runPhantomJs(String path, String command) { Process process; String outFile = "a11.txt"; try { process = Runtime.getRuntime().exec(path+ " " + command + " > " +outFile); int
public void runPhantomJs(String path, String command) {
Process process;
String outFile = "a11.txt";
try {
process = Runtime.getRuntime().exec(path+ " " + command + " > " +outFile);
int exitStatus = process.waitFor();
//String status = (exitStatus == 0 ? "SUCCESS:" : "ERROR:");
File f = new File(outFile);
if (f.exists()) {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f),"UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
脚本执行非常简单,但它会在控制台上返回整个页面:
var webPage = require('webpage');
var page = webPage.create();
page.open('http://www.google.com/', function(status) {
if (status !== 'success') {
console.log('1');
phantom.exit();
} else {
console.log(page.content);
phantom.exit();
}
});
请注意,在粘贴的代码中,我添加了“>a11.txt”,以查看读取文件是否比直接读取输出效果更好。它应该更快,但由于某种原因它不起作用。我想重定向>不起作用 所以我的代码开始工作了。显然,必须读取phantomjs的输出,否则缓冲区将完全填满,从而阻止进一步的执行 因此,我认为如果您这样修改代码,您的代码将正常工作:
process = Runtime.getRuntime().exec(path+ " " + command + " > " +outFile);
BufferedInputStream bis = new BufferedInputStream(process.getInputStream());
bis.close();
process.waitFor();
...
如果不起作用,请尝试使用ProcessBuilder。这是我的工作代码:
试一试{
字符串phantomJsExe=configuration.getPhantomJsExe().toString();
字符串phantomJsScript=configuration.getPhantomJsScript().toString();
字符串urlsTextFile=configuration.getPhantomJsUrlsTextFile().toString()
可能它正在等待您使用输入/输出流。即使没有输入/输出流,也不会到达waitFor()后的断点。waitFor将等待进程结束,因此它应该可以工作。如果我使用更简单的脚本(console.log('success!');有效。在主线程阻塞时,尝试在单独的线程中使用流。如何停止两个线程?
Process process = new ProcessBuilder(phantomJsExe, phantomJsScript, urlsTextFile).start();
BufferedInputStream bis = new BufferedInputStream(process.getInputStream());
bis.close();
process.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}