IO 输入与输出(9)-- Java程序与其他进程的数据通信

    技术2022-05-19  22

    Java程序中,可以启动其他的应用程序,这种在Java中启动的进程称为子进程,启动子进程的Java程序就称为父进程。

     

    Java程序中,可以使用Process类实例对象来表示子进程,子进程的标准输入和输出不再连接到键盘和显示器,而是以管道流的形式连接到父进程的一个输出流和输入流对象上。

     

    调用Process类的getOutputStreamgetInputStream方法可以获得连接到子进程的输出流和输入流对象。

     

    下面直接看一个例子吧:

    TestInOut.java中启动java.exe命令执行另外一个MyTest.javaTestInOut.javaMyTest.java通过进程间的管道相互传递数据。

     

     MyTest.java

     import java.io.*; public class MyTest { public static void main(String[] args) throws IOException { while (true) { String str = new BufferedReader(new InputStreamReader(System.in)) .readLine();// 读取父进程的数据 if (str != null) { System.out.println("re:" + str); //添加回复 } else { return; } } } }

     

    TestInOut.java

     import java.io.*; public class TestInOut implements Runnable { Process process = null; public static void main(String[] args) { TestInOut inOut = new TestInOut(); inOut.send(); } // 向子进程发送数据 public void send() { OutputStream os = process.getOutputStream(); while (true) { try { os.write("hello/r/n".getBytes()); // 不停的写入hello } catch (IOException e) { e.printStackTrace(); } } } // 从子进程读取数据 public void run() { InputStream is = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String strLine; try { while (true) { strLine = br.readLine();// 读取一行信息 if(strLine != null){ System.out.println(strLine); }else{ return; } } } catch (IOException e) { e.printStackTrace(); } } public TestInOut() { try { this.process = Runtime.getRuntime().exec("java MyTest");// 调用java.exe执行"java MyTest"命令 } catch (IOException e) { e.printStackTrace(); } new Thread(this).start(); // 启动一个新的线程 } }

     需要注意的是:在管道缓冲区满了以后,与PipedInputStream相连的PiredOutputStream无法再写入新的数据,PipedOutputStream.write()方法将处于阻塞状态。

     版权声明: 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。


    最新回复(0)