1) java程序与其他进程的通信
package IO;
import java.io.*;
import sun.security.provider.SystemSigner;
public class TestInOut implements Runnable {
Process p=null;//设置一个空进程
public TestInOut()
{
try {
p=Runtime.getRuntime().exec("java MyTest");//遇到问题,无法执行
new Thread(this).start(); //启动接收流的对象
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestInOut tio=new TestInOut();//实例化主程序,调用构造函数,开启读取数据进程
tio.send();//开启输入数据方法
}
public void send()
{
try {
OutputStream ops=p.getOutputStream();//定义输出流
while (true) {
ops.write("help/r/n".getBytes());//写入数据
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void run()
{
try {
int count=0;
InputStream ips=p.getInputStream();//获得输入流
BufferedReader bfr=new BufferedReader(new InputStreamReader(ips));//包装输入流,按行读出
while (true) {
count++;
if(count>50)
{
break;
}
String strLine= bfr.readLine();//按行读取内存
System.out.println(strLine);//打印输出行?
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
调用的进程
package IO;
import java.io.*;
public class MyTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
while (true) {
//System.out.println("我来了");
String strLine=bfr.readLine();
if(strLine!=null)
{
System.out.println("hi:"+strLine);
}
else {
return;
}
}
}
}
问题分析:子进程不能执行
2) 把异常的字符串信息包装后发送出去
package IO;
import java.io.*;
public class TestPrintWriter {
public static void main(String[] args) {
try {
throw new Exception("test");//抛出的异常
} catch (Exception e) {
StringWriter sw=new StringWriter();//声明字符串写入流
PrintWriter pw=new PrintWriter(sw);//包装
e.printStackTrace(pw);//输出异常流
System.out.println(sw.toString());
System.out.println(e.getMessage());
}
}
}