繁体   English   中英

Java中的phantomjs在process.waitFor()中被阻止

[英]phantomjs in Java blocked in process.waitFor()

在Java中使用phantomJs的一个简单示例将无限期阻塞:

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();
    }

}

脚本execute非常简单,但是它在控制台上返回整个页面:

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。 这是我的工作代码:试试{String phantomJsExe = configuration.getPhantomJsExe()。toString(); 字符串phantomJsScript = configuration.getPhantomJsScript()。toString(); 字符串urlsTextFile = configuration.getPhantomJsUrlsTextFile()。toString();

    Process process = new ProcessBuilder(phantomJsExe, phantomJsScript, urlsTextFile).start();
    BufferedInputStream bis = new BufferedInputStream(process.getInputStream());
    bis.close();
    process.waitFor();
} catch (Exception ex) {
    ex.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM