【问题标题】:What is the best/fastest way of calling java jar from php with passing large text?通过传递大文本从 php 调用 java jar 的最佳/最快方法是什么?
【发布时间】:2026-02-07 10:15:02
【问题描述】:

这是场景:我有一个构建 html 并将其回显到浏览器的 php 脚本。就在 html 回显之前,我需要调用可执行的 java jar 文件并将其传递给 html,以便它可以对其进行处理并将其返回给 php 以进行回显。

我现在能想到的唯一方法是将html保存到临时文件,将文件名传递给java,让它修改它并在php中再次加载它。我猜这可能会很慢,需要将文件写入磁盘,然后读取、修改、再次写入并再次读取。

我的问题是:在给定的场景中,是否有更快的方法将 html 文件传递​​给 java 并将其返回给 php?

我当前的堆栈:Apache 2.4、PHP 5.4.7、Java 7、操作系统:Ubuntu

【问题讨论】:

  • proc_open? PHP 用它启动 java 小程序,然后通过 proc 句柄的标准输出将 html 传递给应用程序,标准输出在 java 中显示为标准输入。
  • 谢谢,这看起来很有希望,我只需要找到一个像样的例子,看看它是如何工作的。

标签: java php linux apache


【解决方案1】:

我使用了 Marc B 建议的解决方案,由于网上没有关于这种特殊情况的明确示例,我将粘贴我的 php 和 java 代码以防将来有人需要:

PHP 代码:

<?php

$process_cmd = "java -jar test.jar";

$env = NULL;
$options = ['bypass_shell' => true];
$cwd = NULL;
$descriptorspec = [
    0 => ["pipe", "r"], // stdin is a pipe that the child will read from
    1 => ["pipe", "w"], // stdout is a pipe that the child will write to
    2 => ["pipe", "w"]  // stderr is a file to write to
];

$process = proc_open($process_cmd, $descriptorspec, $pipes, $cwd, $env, $options);

if (is_resource($process)) {

    //feeding text to java
    fwrite($pipes[0], "Test text");
    fclose($pipes[0]);

    //echoing returned text from java
    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    //It is important that you close any pipes before calling
    //proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "\n command returned $return_value\n";
}

?>

JAVA代码:

package Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String input;

        while ((input = br.readLine()) != null) {
            System.out.println(input + " java test string ");
        }

    }

}

【讨论】:

    最近更新 更多