即使子进程退出,java.io.Process 是否保证输出仍然存在?

Does java.io.Process guarantee the output to remain even if the subprocess has exited?

如果 proc 已经退出,输出字符串存储在哪里?

内部缓冲区?

如果内部缓冲区太小无法容纳巨大的字符串怎么办?

能保证不丢失字符串吗?

package Hello;

import java.io.*;

public class Hello {

    public static void main(String args[]) {

        String line = null;

        try {
            ProcessBuilder pb = new 
                ProcessBuilder("command_to_output_huge_strings");

            Process proc = pb.start();
            proc.waitFor();
            //
            // Now proc may have finished its huge output and exited.
            //   

            // Now we want to get the huge strings proc outputed.
            BufferedReader stdInput = new BufferedReader(
                    new InputStreamReader(proc.getInputStream()));
            while ((line = stdInput.readLine()) != null) {
                System.out.println(line);
            }

        } catch (Exception e) {
        }
    }
}
  1. Process.getInputStream().
  2. 中没有缓冲
  3. 进程本身可能存在缓冲。
  4. 进程在刷新其缓冲区之前无法退出。
  5. 您正在调用 Process.waitFor() 然后尝试读取它的输出。
  6. 因此你的问题没有意义,你的代码又回到了前面。您应该阅读所有进程的输出,然后 然后 调用 waitFor().