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

时间:2014-03-04 21:29:54

标签: 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 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”,以查看它是否更适合读取文件而不是直接读取输出。它应该更快,但由于某种原因它不起作用。我想重定向>不起作用。

1 个答案:

答案 0 :(得分:0)

所以我让我的代码工作。显然必须读取phantomjs的输出或缓冲区将完全填满,阻止进一步执行。

所以我认为如果你这样修改你的代码就可以了:

process = Runtime.getRuntime().exec(path+ " " + command + " > " +outFile);
BufferedInputStream bis = new BufferedInputStream(process.getInputStream());
bis.close();
process.waitFor();
...

如果不起作用,请尝试使用ProcessBuilder。这是我的工作代码:     尝试{         String phantomJsExe = configuration.getPhantomJsExe()。toString();         String phantomJsScript = configuration.getPhantomJsScript()。toString();         String 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();
}