关于子进程对象有三个重要的方法。p.getErrorStream(),p.getOutputStream(),p.getInputStream();
package com.huxin.testfifteen.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* 本程序可以解决如何启动一个进程,如何读取一个进程的相关信息。
*/
public class ReadFromProcess {
public static void main(String[] args) {
InputStreamReader is = null;
BufferedReader bf = null;
try {
Process p = Runtime.getRuntime().exec("javac"); //运行javac的命令,并且返回一个子进程的对象。
is = new InputStreamReader(p.getErrorStream()); //返回的是一个字节流
bf = new BufferedReader(is);
String str = null;
while((str = bf.readLine())!=null){
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bf.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.huxin.testfifteen.io;
import java.io.IOException;
import java.io.PrintStream;
/*
* 本程序解决如何启动一个程序,和如何向一个进程写东西。
*/
public class WriteFromProcess {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("java ReadStadard");
PrintStream ps = new PrintStream(p.getOutputStream());
ps.print("我自己写了一点东西,看看能不能写到那个进程中去");
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.huxin.testfifteen.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadStadard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n"); //以回车作为分隔符
PrintStream ps = null;
try {
ps = new PrintStream(new FileOutputStream("D:\\test3.txt"));
while(sc.hasNext()){
ps.print(sc.next()); //如果要写一个字符的话,就用PrintStream的处理流
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
ps.close();
}
}
}