本篇文章為大家展示了在java中寫入管道流上出現報錯如何解決,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

創新互聯公司是工信部頒發資質IDC服務器商,為用戶提供優質的成都服務器托管服務
Java主要應用于:1. web開發;2. Android開發;3. 客戶端開發;4. 網頁開發;5. 企業級應用開發;6. Java大數據開發;7.游戲開發等。
1.創建和連接管道兩端的兩種方法
(1)創建管道輸入和輸出流并連接它們。它使用connect方法連接兩個流。
PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); pis.connect(pos); /* Connect the two ends */
(2)創建管道輸入和輸出流并連接它們。它通過將輸入管道流傳遞到輸出流構造器來連接兩個流。
PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(pis);
2.寫入報錯分析
在線程Sender中向管道流中寫入一個字符串,寫入后關閉該管道流;在線程Reciever中讀取該字符串。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class PipedStreamExam1 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
try {
//創建管道流
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
//創建線程對象
Sender sender = new Sender(pos);
Reciever reciever = new Reciever(pis);
//運行子線程
executorService.execute(sender);
executorService.execute(reciever);
} catch (IOException e) {
e.printStackTrace();
}
//等待子線程結束
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Sender extends Thread {
private PipedOutputStream pos;
public Sender(PipedOutputStream pos) {
super();
this.pos = pos;
}
@Override
public void run() {
try {
String s = "This is a good day. 今天是個好天氣。";
System.out.println("Sender:" + s);
byte[] buf = s.getBytes();
pos.write(buf, 0, buf.length);
pos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class Reciever extends Thread {
private PipedInputStream pis;
public Reciever(PipedInputStream pis) {
super();
this.pis = pis;
}
@Override
public void run() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = pis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
byte[] result = baos.toByteArray();
String s = new String(result, 0, result.length);
System.out.println("Reciever:" + s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}注意,若管道流沒有關閉,則使用這種方法讀取管道中的信息會報錯:
while ((len = pis.read(buf)) != -1) {
baos.write(buf, 0, len);
}錯誤代碼為java.io.IOException: Write end dead;發生這個錯誤的原因在于,由于管道未關閉,所以read語句不會讀到-1,因此PipedInputStream會持續從管道中讀取數據,但是因為Sender線程已經結束,所以會拋出“Write end dead”異常。
上述內容就是在java中寫入管道流上出現報錯如何解決,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注創新互聯行業資訊頻道。
當前標題:在java中寫入管道流上出現報錯如何解決
URL分享:http://www.yijiale78.com/article14/jcsgde.html
成都網站建設公司_創新互聯,為您提供靜態網站、企業網站制作、營銷型網站建設、企業建站、標簽優化、手機網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯