我计划在我的Java程序中使用PHP库,方法是创建一个PHP CLI交互式shell,其中包含我需要的所有函数的命令,然后从Java调用它们。大多数命令会将一个String打印到控制台,然后我将用Java解析我需要的数据。
目前我的Java代码如下所示:
ProcessBuilder builder = new ProcessBuilder(
"Q:\\Instagram\\new\\php.bat", "main.php");
builder.directory(new File("Q:\\Instagram\\new"));
builder.redirectErrorStream(true);
Process p = builder.start();
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
System.out.println("The first output is: ");
Scanner scanner = new Scanner(reader);
while (scanner.hasNextLine()) {
System.out.println("Output: " + scanner.nextLine());
}
writer.flush();
writer.write("Test two");
writer.newLine();
System.out.println("The second output is: ");
scanner = new Scanner(reader);
while (scanner.hasNextLine()) {
System.out.println("Output: " + scanner.nextLine());
}
我的PHP脚本main.php是:
<?php
print_r("Test One\n");
print_r(fgets(STDIN));
?>
使用此代码,输出为空,程序继续运行。
当我从PHP文件中删除print_r(fgets(STDIN));
时,它输出:
The first output is:
Output:
Output: Q:\Instagram\new>Q:\Robobot\PHP\php.exe main.php main.php0
Output: Test one
The second output is:
Process finished with exit code 0
现在叫我傻了,但如果我没有删除那条线,它应该输出吗?
The first output is:
Output:
Output: Q:\Instagram\new>Q:\Robobot\PHP\php.exe main.php main.php0
Output: Test one
The second output is:
然后等待Java代码执行:
writer.flush();
writer.write("Test two");
writer.newLine();
最后输出:
Test two
Test two
Process finished with exit code 0
(测试二显示两次,因为第一次是输入到控制台,第二次是PHP脚本重复它)
有些方面的信息,我在IntelliJ上的Windows上做这个,但我打算最终在Ubuntu上运行它。上面的例子来自我从IntelliJ内部运行它,但是当我从命令行运行它时我得到了相同的结果。