Тръби в IO осигурява връзка между две нишки, работещи в JVM едновременно. Така че каналите се използват както като източник, така и като дестинация.
PipedInputStream също се препраща с PipedOutputStream. Така че данните могат да се записват с помощта на PipedOutputStream и могат да се записват с помощта на PipedInputStream. Но използването на двете нишки едновременно ще създаде задънена улица за нишките.
Твърди се, че една тръба е прекъсната, ако нишка, която е предоставяла байтове данни към свързания канален изходен поток, вече не е жива.
Декларация:
public class PipedInputStream extends InputStream
Конструктор:
PipedInputStream() :
създава PipedInputStream, че не е свързан.
PipedInputStream(int pSize):
създава PipedInputStream, че не е свързан с определен размер на тръбата.
PipedInputStream(PipedOutputStream outStream) :
създава PipedInputStream, че е свързан с PipedOutputStream - 'outStream'.
PipedInputStream(PipedOutputStream outStream int pSize) :
създава Piped Input Stream, който е свързан с Piped Output Stream с посочения размер на тръбата. Методи:
int read():
Reads the next byte of data from this piped input stream.The value byte is returned as an int in the range 0 to 255. This method blocks until input data is available the end of the stream is detected or an exception is thrown. Java
// Java program illustrating the working of read() methodimportjava.io.*;publicclassNewClass{publicstaticvoidmain(String[]args)throwsIOException{PipedInputStreamgeek_input=newPipedInputStream();PipedOutputStreamgeek_output=newPipedOutputStream();try{// Use of connect() : connecting geek_input with geek_outputgeek_input.connect(geek_output);// Use of read() method :geek_output.write(71);System.out.println('using read() : '+(char)geek_input.read());geek_output.write(69);System.out.println('using read() : '+(char)geek_input.read());geek_output.write(75);System.out.println('using read() : '+(char)geek_input.read());}catch(IOExceptionexcept){except.printStackTrace();}}}
Изход:
using read() : G using read() : E using read() : K
read(byte[] buffer int offset int maxlen) :
java.io.PipedInputStream.read(byte[] buffer int offset int maxlen) чете до maxlen байта от данните от Piped Input Stream в масива от буфери. Методът блокира, ако бъде достигнат краят на потока или е хвърлено изключение. Синтаксис:
public int read(byte[] buffer int offset int maxlen) Parameters : buffer : the destination buffer into which the data is to be read offset : starting in the destination array - 'buffer'. maxlen : maximum length of array to be read Return : next 'maxlen' bytes of the data as an integer value return -1 is end of stream is reached Exception : -> IOException : if in case IO error occurs. -> NullPointerException : if buffer is null. -> IndexOutOfBoundsException : if offset is -ve or maxlen is -ve or maxlen > buffer.length - offset.
получи (int байт):
java.io.PipedInputStream.receive(int байт) получава байт от данните. Ако няма наличен вход, тогава методът блокира. Синтаксис:
protected void receive(int byte) Parameters : byte : the bytes of the data received Return : void Exception : -> IOException : if in case IO error occurs or pipe is broken.
затвори():
java.io.PipedInputStream.close() затваря конвейерния входен поток и освобождава разпределените ресурси. Синтаксис:
public void close() Parameters : -------------- Return : void Exception : -> IOException : if in case IO error occurs.
свързване (източник на PipedOutputStream):
java.io.PipedInputStream.connect(източник на PipedOutputStream) свързва Piped Input Stream към 'source' Piped Output Stream и в случай че 'source' е канали с някакъв друг поток, се хвърля IO изключение Синтаксис:
public void connect(PipedOutputStream source) Parameters : source : the Piped Output Stream to be connected to Return : void Exception : -> IOException : if in case IO error occurs.
наличен():
java.io.PipedInputStream.available() връща не. от байтове, които могат да бъдат прочетени от Input Stream, без всъщност да бъдат блокирани. Синтаксис:
public int available() Parameters : ------------- Return : no. of bytes that can be read from Input Stream without actually being blocked. 0 if the stream is already closed but by invoking close() method Exception : -> IOException : if in case IO error occurs.
Java програма, обясняваща работата на методите на клас PipedInputStream: Java
// Java program illustrating the working of PipedInputStream// connect() read(byte[] buffer int offset int maxlen)// close() available()importjava.io.*;publicclassNewClass{publicstaticvoidmain(String[]args)throwsIOException{PipedInputStreamgeek_input=newPipedInputStream();PipedOutputStreamgeek_output=newPipedOutputStream();try{// Use of connect() : connecting geek_input with geek_outputgeek_input.connect(geek_output);geek_output.write(71);geek_output.write(69);geek_output.write(69);geek_output.write(75);geek_output.write(83);// Use of available() :System.out.println('Use of available() : '+geek_input.available());// Use of read(byte[] buffer int offset int maxlen) :byte[]buffer=newbyte[5];// destination 'buffer'geek_input.read(buffer05);Stringstr=newString(buffer);System.out.println('Using read(buffer offset maxlen) : '+str);// USe of close() method :System.out.println('Closing the stream');geek_input.close();}catch(IOExceptionexcept){except.printStackTrace();}}}
Изход:
Use of available() : 5 Using read(buffer offset maxlen) : GEEKS Closing the stream
Next Article: Клас Java.io.PipedOutputStream в Java Създаване на тест