// Test1.java文件 import java.io.*; public class Test { public static void main(String[] args) { FileOutputStream fOut = new FileOutputStream("c:\\Test1.txt"); fOut.close(); System.out.println("被调用成功!"); } } // Test_Exec.java public class Test_Exec { public static void main(String[] args) { Runtime run = Runtime.getRuntime(); Process p = run.exec("java test1"); } } |
// Test_Exec_Out.java import java.io.*; public class Test_Exec_Out { public static void main(String[] args) { Runtime run = Runtime.getRuntime(); Process p = run.exec("java test1"); BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while ((s = br.readLine()) != null) System.out.println(s); } } |
// Test2.java文件 import java.io.*; public class Test { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("由父进程输入的信息:" + br.readLine()); } } // Test_Exec_In.java import java.io.*; public class Test_Exec_In { public static void main(String[] args) { Runtime run = Runtime.getRuntime(); Process p = run.exec("java test2"); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); bw.write("向子进程输出信息"); bw.flush(); bw.close(); // 必须得关闭流,否则无法向子进程中输入信息 // System.in.read(); } } |
// Test_Exec_Out.java import java.io.*; public class Test_Exec_Out { public static void main(String[] args) { ProcessBuilder pb = new ProcessBuilder("java", "test1"); Process p = pb.start(); … … } } |
ProcessBuilder pb = new ProcessBuilder("Command", "arg2", "arg2", '''); // 设置环境变量 Map<String, String> env = pb.environment(); env.put("key1", "value1"); env.remove("key2"); env.put("key2", env.get("key1") + "_test"); pb.directory("..\abcd"); // 设置工作目录 Process p = pb.start(); // 建立子进程 |