日期:2014-05-20 浏览次数:20780 次
import java.io.*; 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() { //int count=0; try { OutputStream os=p.getOutputStream(); while(true) { // System.out.println(++count); os.write("help\r\n".getBytes()); } }catch(Exception e) { e.printStackTrace(); } } public void run() { try { InputStream in=p.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(in)); while(true) { String strLine=br.readLine(); if(strLine!=null) System.out.println(strLine); else return; } }catch(Exception e) { e.printStackTrace(); } } }
import java.io.*; public class MyTest { public static void main(String []args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(true) { // System.out.println("Hi:"+new BufferedReader(new InputStreamReader(System.in)).readLine());//原始状态 // String strLine=new BufferedReader(new InputStreamReader(System.in)).readLine();//修改状态 String strLine=br.readLine(); if(strLine!=null) System.out.println("Hi:"+strLine); else return; } } }
import java.io.*; public class MyTest { public static void main(String[] args) throws Exception { //获取控制台的流,包装为BufferedReader,方便正行读取 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { // System.out.println("Hi:"+new BufferedReader(new // InputStreamReader(System.in)).readLine());//原始状态 // String strLine=new BufferedReader(new // InputStreamReader(System.in)).readLine();//修改状态 //控制台中读取一行,返回null表示结束 String strLine = br.readLine(); //如果没有结束,答应Hi + 输入的信息 if (strLine != null) System.out.println("Hi:" + strLine); //否则退出程序 else return; } } }
------解决方案--------------------
import java.io.*; class TestInOut implements Runnable { Process p = null; public TestInOut() { try { // 运行My Test 监听MyTest输入输出 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() { // int count=0; try { // 输出流,往My Test循环发送help的信息 OutputStream os = p.getOutputStream(); while (true) { // System.out.println(++count); os.write("help\r\n".getBytes()); } } catch (Exception e) { e.printStackTrace(); } } public void run() { try { // 输入流,获取My Test的输出 InputStream in = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); while (true) { String strLine = br.readLine(); if (strLine != null) System.out.println(strLine); else return; } } catch (Exception e) { e.printStackTrace(); } } }