【基礎篇】java中輸入輸出的總括——管道流

來源:互聯網
上載者:User
 

不想把別人的東西佔為己有,但是想方便日後參考還是摘錄了。

煩死了,看Java編程思想三或者四,感覺老外寫書跟我們看書的習慣都不一樣的,總感覺老外寫的東西就像是在寫手冊,全面但是煩瑣。

【原則】不要告訴我曆史,告訴我怎麼做就行了。

【事實】輸出輸入類,就是TMD的簡單,為什麼非要弄成手冊,讓我這個菜鳥看不懂

【鳴謝】中國IT實驗室的總結篇

 ——————————————————————————————————————————————————————————

管道流

管道用來把一個程式、線程和代碼塊的輸出串連到另一個程式、線程和代碼塊的輸入。java.io中提供了類PipedInputStream和PipedOutputStream作為管道的輸入/輸出流
管道輸入資料流作為一個通訊管道的接收端,管道輸出資料流則作為發送端。管道流必須是輸入輸出並用,即在使用管道前,兩者必須進行串連
管道輸入/輸出流可以用兩種方式進行串連:
–     在構造方法中進行串連
•     PipedInputStream(PipedOutputStream pos);
•     PipedOutputStream(PipedInputStream pis);
–     通過各自的connect()方法串連
•     在類PipedInputStream中,connect(PipedOutputStream pos);
     
•     在類PipedOutputStream中,connect(PipedInputStream pis);
例 8.8 管道流。
本例例管道流的使用方法。設輸入管道in與輸出管道out已串連,Send線程向輸出管道out發送資料,Receive線程從輸入管道in中接收資料。程式如下:
import java.io.*;
public class Pipedstream
{
public static void main (String args[])
{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
try
{
in.connect(out);
}
catch(IOException ioe) { }
Send s1 = new Send(out,1);
Send s2 = new Send(out,2);
Receive r1 = new Receive(in);
Receive r2 = new Receive(in);
s1.start();
s2.start();
r1.start();
r2.start();
}
}
class Send extends Thread //發送線程
{
PipedOutputStream out;
static int count=0; //記錄線程個數
int k=0;
public Send(PipedOutputStream out,int k)
{
this.out= out;
this.k= k;
this.count++; //線程個數加1
}
public void run( )
{
System.out.print("/r/nSend"+this.k+": "+this.getName()+" ");
int i=k;
try
{
while (i<10)
{
out.write(i);
i+=2;
sleep(1);
}
if (Send.count==1) //只剩一個線程時
{
out.close(); //關閉輸入管道流
System.out.println(" out closed!");
}
else
this.count--; //線程個數減1
}
catch(InterruptedException e) { }
catch(IOException e) { }
}
}
class Receive extends Thread //接收線程
{
PipedInputStream in;
public Receive(PipedInputStream in)
{
this.in = in;
}
public void run( )
{
System.out.print("/r/nReceive: "+this.getName()+" ");
try
{
int i = in.read();
while (i!=-1) //輸入資料流未結束時
{
System.out.print(i+" ");
i = in.read();
sleep(1);
}
in.close(); //關閉輸入管道流
}
catch(InterruptedException e) { }
catch(IOException e)
{
System.out.println(e);
}
}
}
程式運行結果如下:
Send1: Thread-0
Send2: Thread-1
Receive: Thread-2 1
Receive: Thread-3 2 3 4 5 7 out closed!
6 8 9 java.io.IOException: Pipe closed!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.