Byte stream summary, byte stream Summary

Source: Internet
Author: User

Byte stream summary, byte stream Summary

Byte stream Summary

InputStream (Abstract class: indicates the parent class of all byte input streams.)

|-FileInputStream (It is mainly used for raw byte streams such as image data.)

|-FilterInputStream (Simple RewritingInputStreamMethod)

|-BufferedInputStream (Provide buffering and other functions)

|-PipedInputStream (Mainly used for Multithreading)

OutputStream (Abstract class: indicates the parent class of all byte output streams.)

|-FileOutputStream (It is mainly used for raw byte streams such as image data.)

|-FilterOutputStream (Simple RewritingOutputStreamMethod)

|-BufferedOutputStream (Provide buffering and other functions)

|-PrintStream (Print all kinds of data worth Representation)

|-PipedOutputStream (Mainly used for Multithreading)

 

1AboutBufferedInputStreamAndFileInputStreamDifference

InFileInputStreamIt indicates that this method will be blocked, that is, when you read a file input stream, when you read a location, if you do some other processing (such as accepting some bytes for some processing), at this time, the input stream will not continue to read at what position andBufferedInputStreamAlthough there is alsoReadMethod, but it can be seen from the name that it has a buffer, it is a non-blocking method, when you read a location, do some processing, the input stream may continue to read bytes, which achieves the buffer effect.

Public class SS {
Public static void main (String [] args) throws Exception {
File f = new File ("d :\\
Large database files. Mdf ");
FileInputStream FCM = new FileInputStream (f );
//
If the following statement usesBufferedOutputStreamTo improve the performance.
FileOutputStream fos = new FileOutputStream ("e: \" + f. getName ());
Int length = 0;
Byte [] B = new byte [1024];
While (length = FS. read (B ))! =-1)
{
Fos. write (B, 0, length );
}
Fos. close ();
FCM. close ();
}
}

2, Pipeline flow

When you need to read and write data in two threads, the synchronization of read and write may be difficult due to concurrent execution of the thread. At this time, you can use pipelines, which are actually a queue.

The MPs queue is a buffer maintained by the system. Of course, the programmer can directly specify the buffer size (onlyPIPE_SIZEAttribute value ). After the producer generates data, it only needs to write the data to the MPs queue, and the consumer only needs to read the required data from the MPs queue. Using this mechanism of pipelines, the output results of one thread can be directly connected to the input port of another thread to realize direct data transfer between the two.

Thread1
Thread2
Temporary Files
MPs queue

MPs queue connection:

One method is to directly use the output of a program as the input of another program through the constructor, and specify the target pipeline object when defining the object.

PipedInputStream pInput = new PipedInputStream ();

PipedOutputStream pOutput = new PipedOutputStream (pInput );

The second method is to use any member function in both classes.Connect ()Connected

PipedInputStream pInput = new PipedInputStream ();

PipedOutputStream pOutput = new PipedOutputStream ();

Pinput. connect (pOutput );

MPs queue input and output:

Call the output MPs queue objectWrite ()The member function outputs data (that is, the data is sent to the input end of the pipeline), while the input pipeline object callsRead ()Member functions can read data (that is, obtain data from the output pipeline ). This is mainly achieved through the system's buffer mechanism.

Instance:JavaMPs queue Input and Output

Import java. io .*;

Public class PipedIO //RunSendFileCopy the object contentReceiverFileFile

{

Public static void main (String args [])

{

Try

{

//Construct a read/write pipeline Stream Object

PipedInputStream pis = new PipedInputStream ();

PipedOutputStream pos = new PipedOutputStream ();

//Implement Association

Pos. connect (pis );

//Construct two threads and start them.

New Sender (pos, "c: \ text2.txt"). start ();

New Explorer (pis, "c: \ text3.txt"). start ();

}

Catch (IOException e)

{

System. out. println ("Pipe Error" + e );

}

}

}

//Thread sending

Class Sender extends Thread

{

PipedOutputStream pos;

File file;

//Constructor

Sender (PipedOutputStream pos, String fileName)

{

This. pos = pos;

File = new File (fileName );

}

//Thread running Method

Public void run ()

{

Try

{

//Read File Content

FileInputStream fs = new FileInputStream (file );

Int data;

While (data = fs. read ())! =-1)

{

//Write the beginning of the Pipeline

Pos. write (data );

}

Pos. close ();

}

Catch (IOException e)

{

System. out. println ("Sender Error" + e );

}

}

}

//Thread read

Class extends er extends Thread

{

PipedInputStream pis;

File file;

//Constructor

Extends Er (PipedInputStream pis, String fileName)

{

This. pis = pis;

File = new File (fileName );

}

//Thread running

Public void run ()

{

Try

{

//Write File Stream Object

FileOutputStream fs = new FileOutputStream (file );

Int data;

//Read from the end of the MPs queue

While (data = pis. read ())! =-1)

{

//Write local files

Fs. write (data );

}

Pis. close ();

}

Catch (IOException e)

{

System. out. println ("er Error" + e );

}

}

}

3. PrintStream and PrintWriter

Based on OutputStream, PrintStream provides enhanced functions, that is, it can easily output formatted representations of various types of data (not limited to bytes. The PrintStream method never throws IOEceptin.

PrintWriter provides all PrintStream printing methods and never throws IOException. Difference from PrintStream: when processing a stream, PrintStream can only encapsulate the byte stream of the OutputStream type, while PrintWriter can encapsulate the byte stream of the OutputStream type, it can also encapsulate Writer-type character output streams and enhance its functions.

Class IODemo{

Public static void main (String [] args){

Try{

FileReader fr = new FileReader ("a.txt ");

BufferedReader br = new BufferedReader (fr );

FileWriter fw = new FileWriter ("33.txt ");

PrintWriter pw = new PrintWriter (fw );

String s = br. readLine ();

While (null! = S){

// The println method of PrintWriter is equivalent

// Write () + newLine () of BufferedWriter ()

Pw. println (s );

S = br. readLine ();

}

Br. close ();

Pw. close ();

}Catch (IOException e){

E. printStackTrace ();

}

}

}

If you replace PrintWriter with PrintStream, an error is returned because PrintStream can only encapsulate byte streams and cannot encapsulate Writer class objects.

Note: If you have special requirements on the output stream format, it is easier to use PrintStream and PrintWriter.

4,InputStream Data Reading

AboutInputStream. read ()
When reading data from a data stream, the diagram is simple and often usedInputStream. read ()Method. This method reads only one byte from the stream at a time, and the efficiency is very low.A better way is to useInputStream. read (byte [] B)OrInputStream. read (byte [] B, int off, int len)Method To read multiple bytes at a time.


AboutInputStreamClassAvailable ()Method
It is often used to read multiple bytes at a time.InputStream. available ()Method, this method can first know how many bytes can be read in the data stream before reading and writing operations. Note that if this method is used in the slave
When reading data from local files, there is usually no problem, but if it is used for network operations, it will often encounter some troubles. For example,SocketDuring communication, Fang Ming sent1000Bytes, but your program callsAvailable ()Method, but only get900, Or100, Or even0It seems a bit confusing. Why cannot it be found. In fact, this is because network communication is often intermittent, and a string of bytes is often sent in batches. Local program callAvailable ()The method is sometimes obtained0This may be because the other party has not responded or the other party has responded, but the data has not yet been delivered to the local device. The recipient has sent1000Bytes for you, maybe divided3Batch Arrival, you need to call3TimesAvailable ()Method to obtain the total number of data.
If you write code like this:
Int count = in. available ();
Byte [] B = new byte [count];
In. read (B );
Network operations often fail because you callAvailable ()Method, the sent data may not arrive.CountYes0.
You need to change it to the following:
Int count = 0;
While (count = 0 ){
Count = in. available ();
}
Byte [] B = new byte [count];
In. read (B );
AboutInputStream. read (byte [] B)AndInputStream. read (byte [] B, int off, int len)Both methods are used to read multiple bytes from the stream. experienced programmers will find that these two methods are often used.The number of bytes that cannot be read. For example, in the first method, programmers often want the program to readB. lengthBytes, but the actual situation is that the system often cannot read so much. Read carefullyJavaOfAPIThis method is found.It is not guaranteed that so many bytes can be read. It can only ensure that so many bytes can be read at most.(Minimum1Items). Therefore, if you want the program to readCountThe following code is recommended:
Byte [] B = new byte [count];
Int readCount = 0 ;//
Number of successfully read bytes
While (readCount <count ){
ReadCount + = in. read (bytes, readCount, count-readCount );
}
Use this code to ensure readCountBytes, unless you encounterIOException or the end of the data stream(EOFException)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.