I'm planning to use a PHP library in my Java program by making a PHP CLI interactive shell with commands for all the functions I need, and then calling those from Java. Most of the commands will print a String to the console which I'll then parse in Java to the data I need.
Currently my Java code looks like this:
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());
}
And my PHP script, main.php, is:
<?php
print_r("Test One\n");
print_r(fgets(STDIN));
?>
With this code the output is empty, and the program keeps running.
When I remove print_r(fgets(STDIN));
from the PHP file it outputs:
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
Now call me stupid, but should it output this if I didn't remove that line?
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:
Then wait for the Java code to do:
writer.flush();
writer.write("Test two");
writer.newLine();
And then finally output:
Test two
Test two
Process finished with exit code 0
(Test two is show twice since the first time is the input into the console, and the second time the PHP script repeating it)
Some side info, I'm making this on Windows in IntelliJ but I plan on running it on Ubuntu eventually. The examples above are from me running it from inside IntelliJ, but I got the same result when I ran it from the command line.