本帖最后由 韩伟 于 2012-8-1 20:02 编辑
我在做管道输入练习时发现一个这样的问题,请大家来指点一下:- import java.io.*;
- class PipedOutputStreamDemo
- {
- public static void main(String []args) throws IOException
- {
- PipedInputStream in = new PipedInputStream();
- PipedOutputStream out = new PipedOutputStream();
- in.connect(out);
- Read r = new Read(in);
- Write w = new Write(out);
- Thread p1 = new Thread(r);
- Thread p2 = new Thread(w);
- p1.start();
- p2.start();
- }
- }
- class Read implements Runnable
- {
- private PipedInputStream in = new PipedInputStream();
-
- public void run()
- {
- try
- {
- byte [] buf = new byte[1024]; <font color="red"> //这里如果是Byte [] buf = new Byte[1024]时,
- // String s = new String(buf,0,len);这句话就回出错,
- //这是为什么呢,难道他们不一样吗?</font>
- int len = in.read(buf); <font color="red"> //还有一点儿就是好像并不存在read(byte[]b)这个方法,
- //又没有说明<strong>read</strong>(byte[] b, int off, int len)
- //方法的后面两个参数可以缺省,为什么可以这样用呢?</font>
- String s = new String(buf,0,len);
- System.out.println(s);
- in.close();
- }
- catch(IOException e)
- {
- throw new RuntimeException("Read Error!");
- }
- }
-
- Read(PipedInputStream in)
- {
- this.in = in;
- }
- }
- class Write implements Runnable
- {
- private PipedOutputStream out = new PipedOutputStream();
-
- Write(PipedOutputStream out)
- {
- this.out = out;
- }
- public void run()
- {
- try
- {
- out.write("piped come on!".getBytes());
- out.close();
- }
- catch(IOException e)
- {
- throw new RuntimeException ("Write Error!");
- }
- }
- }
复制代码 |
|