package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class StartPhpProcess {
    public static void main(String[] args) throws IOException, InterruptedException {
        List<String> commands = new ArrayList();
        commands.add("php");
        commands.add("worker.php");
        ProcessBuilder pb = new ProcessBuilder();
        pbmand(commands);
        pb.directory(new File("/home/gt/workspace/JavaPhp/src/test"));
        Process worker = pb.start();
        OutputStreamWriter out = new OutputStreamWriter(worker.getOutputStream());
        out.write("1234\n");
        out.flush();

        StringBuilder result = new StringBuilder();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(worker.getInputStream()));
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("!!!"+line);
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        worker.waitFor();
        int exit = worker.exitValue();
        if (exit != 0) {
            throw new IOException("failed to execute:" + pbmand() + " with result:" + result);
        } 
        System.out.println(result.toString());
    }
}
<?php
$stdin = fopen('php://stdin','r');
$line = fgets($stdin);
print $line;

更多推荐

Java 调用 PHP 实例