首页 > 解决方案 > 如何使用命令行在 php 中使用 System.in 输入运行 Java

问题描述

现在是周末,我正在开始一个新项目为了成为项目的核心部分,我需要使用 php使用 System.in(或其他,如果有其他更好的选择)执行面向性能的 Java

我已经将我的 php 与 exec 和 popen 与我的 java 类连接起来,但是在一次执行之后,它会启动另一个 java.class 与之前的完全相同,而不是再次将它提供给 with System.in waiting java

我的.php文件

    var_dump(exec('"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" -Dfile.encoding=UTF-8 -classpath C:\xampp\htdocs\programmierzeugs\phpCallsJava\bin\production\java test');

    var_dump(exec('"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" -Dfile.encoding=UTF-8 -classpath C:\xampp\htdocs\programmierzeugs\phpCallsJava\bin\production\java test hi');

和我的 Java 类

    public static void main(String[] args){
        System.out.println("test123");
        Scanner scanner = new Scanner(System.in);

        String line = scanner.nextLine();
        System.out.println(line);

输出是:

string(7) "test123"  
string(7) "test123"

通过@MDuh 的建议,我将程序更改为:

$handle = proc_open('"C:\Program Files\Java\jdk-12.0.1\bin\java.exe" -Dfile.encoding=UTF-8 -classpath C:\xampp\htdocs\programmierzeugs\phpCallsJava\bin\production\java test',
    [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'r']], $pipes);

if ($err = stream_get_contents($pipes[2]))
{
    echo $err;
} else {
    var_dump(fread($pipes[0], 6));
    echo (string) fwrite($pipes[1], 'hi');
    var_dump(fread($pipes[1], 3));
}

以下问题:
在我读取超过 7 个字符后(测试字符串是 'test123'),fread()随机使我死锁(有时不会)并stream_get_cotents()立即执行。Fwrite 给了我一个错误,我猜这就是为什么我没有什么可读的

标签: javaphpcommand-linesystem.in

解决方案


推荐阅读