本帖最后由 李知伦 于 2012-8-9 19:05 编辑
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- public class TestInOut implements Runnable
- {
- Process p=null;
- public TestInOut()
- {
- try
- {
- p=Runtime.getRuntime().exec("java MyTest");
- new Thread(this).start();
- }
- catch(IOException 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)
- {
- //int len=0;
- //String str="help\r\n";
- //byte[] buf= str.getBytes();
- //len=buf.length;
- //ops.write(buf,0,len);
- ops.write("help\r\n".getBytes());<font color="Red">//q1.这行eclipse管道已结束,并且继续不停输出null</font>
- }
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
- }
- public void run()
- {
- try
- {
- InputStream in = p.getInputStream();
- BufferedReader bfr=new BufferedReader(new InputStreamReader(in));
- while(true)
- {
- String strLine=bfr.readLine();
- <font color="Lime">//if(strLine!=null)</font>
- System.out.println(strLine);
- <font color="Lime">//else
- //return;</font>
- }
- }
- catch(IOException e)
- {
- e.printStackTrace();
- p.destroy();
- }
- }
- }
- class MyTest
- {
- public static void main(String [] args)
- {
- BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
- while(true)
- {
- try {
- <font color="Lime">//if(bfr.readLine()!=null)</font>
- System.out.println("hi:"+bfr.readLine());
- <font color="Lime"> //else
- //return;</font>
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- <font color="Lime">//bfr.close();//q2</font>
- }
- }
- }
复制代码 Eclipse的输出:
java.io.IOException: 管道已结束。
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.write(Unknown Source)
at java高级02_IO输入与输出.TestInOut.send(TestInOut.java:43)
at java高级02_IO输入与输出.TestInOut.main(TestInOut.java:28)
两个问题
q1.这一讲,张老师讲的时候用JCreator说运行它有问题,要在控制台中运行成功,我用的Eclipse就会报异常
q2.老师还说,不能在//q2关闭流,但是如果程序编不好,就会在windo进程中残留java.exe占用大量cpu
为什么我加上下面代码就不会出现这个问题
如果用Process的destroy方法,应该用在哪
if(strLine!=null)
//codes
else
return;
|