The difference between byte stream and character stream in Java

Source: Internet
Author: User

BYTE stream

In the I/O class library, Java.io.InputStream and java.io.OutputStream represent byte input streams and byte output streams, which are abstract classes that cannot be instantiated, and the smallest unit in the data flow is bytes, so it is called a byte stream.

The method of reading data in InputStream is as follows:

1, int read ()

Function: Reads a byte of data, and returns the read data, and if 1 is returned, it reads to the end of the input stream.

2, int read (byte[] b)

Function: Reads a certain amount of bytes from the input stream, stores it in byte array B, returns the number of bytes actually read, or returns 1, which indicates that the end of the input stream is read.

3, int read (byte[] b, int off, int len)

Function: Reads the data into a byte array, returns the actual number of bytes read, and returns 1 if it is read to the end of the input stream. OFF specifies the starting offset where the data is stored in array B, and Len specifies the maximum number of bytes to read.

4, available ()

Function: Returns the number of estimated bytes that a method call can read from or skip from this input stream without blocking.

5. Close ()

Function: Closes the input stream, releasing the associated resources for this stream.

Second, the method of writing data in OutputStream is as follows:

1, int write (int b)

Function: Writes the lowest byte of B to this input stream, and the other three bytes are discarded.

2, int write (byte[] b)

Function: Writes the specified byte array b to this input stream.

3, int write (byte[] b, int off, int len)

Function: Writes Len bytes from offset off to the input stream in the specified byte array.

4. Flush ()

Function: refreshes this input stream and forces the output bytes of all buffers to be written out.

5. Close ()

Function: Closes the output stream, releasing the associated resources for this stream.

Character Stream

is an IO operation in characters, one character is two bytes, and the largest two parent class is the abstract class of writer and reader.

When it comes to methods in the abstract class of byte stream and character stream, the method name, the return value type, etc. are similar, except that the write () method that passes in the parameter partial byte stream needs to pass in a character array (string also a character array) that needs to be passed in the write () method of the bytes array character stream. )

But we all know that character arrays and byte arrays are easily interchanged by GetBytes () and new String ().

What is the main difference between a byte stream and a character stream?

One. The byte stream does not use buffers (memory) when it is operated, and it operates directly on the file itself. The character stream uses a buffer to manipulate the file through the buffer.

Two. All files on the hard disk are in bytes (picture, sound, video), and character values are formed in memory.

Analytical:

For the 1th,

If a program frequently makes an IO operation on a resource, the efficiency is very low. At this point, through the buffer, the data needs to be temporarily put into memory, and then read directly from memory, you can avoid multiple IO operations, improve efficiency

For the 2nd,

When the data is actually stored and transmitted in bytes, the characters exist only in memory, so the byte stream can be used more broadly.

Three. Note: The character stream is actually converted into a byte stream and then IO operation

We know that both reader and writer are abstract classes, and for specific operations, they need to be manipulated in a way that is implemented in a specific implementation class, using polymorphism.

Package Com.lw.inputstream;import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import java.io.IOException;/*copy a picture to another place. */ Public classDemo3 {/** * @param args * @throws ioexception*/     Public Static voidMain (string[] args) throws IOException {//TODO auto-generated Method StubCopeimage (); }         Public Static voidCopeimage () throws ioexception{//read and write again. //Whether you are using an output stream or an input stream, the operation must be a file. //1. Reading data//input byte stream//1. Find the picture you want to copyFile File =NewFile ("d:\\images\\01.jpg");//notfoundexceptionFileInputStream InputStream =Newfileinputstream (file); File file1=NewFile ("d:\\01.jpg"); FileOutputStream OutputStream=NewFileOutputStream (FILE1); byte[] B =New byte[1024x768]; //int count = 0;         while(Inputstream.read (b)!=-1){            //2. Writing Data//Output byte streamOutputstream.write (b); }                //the principle of closing flow off flow: first open and then off. Outputstream.close ();                                            Inputstream.close (); }}

1  PackageCom.lw.InputStream;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 Importjava.io.FileNotFoundException;6 Importjava.io.IOException;7  Public classDemo1 {8 9     /**Ten      * @paramargs One      * @throwsIOException A      */ -      Public Static voidMain (string[] args)throwsIOException { -         //TODO auto-generated Method Stub the   - getFile4 (); -     } -      +     //mode four: read by creating buffers and loops -      Public Static voidGetFile4 ()throwsioexception{ +           //Get start time: A           LongStartTime =System.currenttimemillis (); at           //1. Find the target file -File File =NewFile ("D:\\images\\01.jpg"); -           //2. Establishing a channel -FileInputStream FileInputStream =Newfileinputstream (file); -           //3. Create a buffer -           //3k in           byte[] B =New byte[1024];//generally write 1024 times times the larger the buffer is theoretically set, the higher the efficiency of reading -           //4. Reading data to           intCount = 0; +            while(count = Fileinputstream.read (b))!=-1){ -                theSystem.out.println (NewString (b,0, Count)); *           } $           //5. Close ResourcesPanax Notoginseng fileinputstream.close (); -         //End Time the             LongEndTime =System.currenttimemillis (); +                      ASystem.out.println ("Time Spent:" + (Endtime-starttime));//399 nearly 20 times the}

The difference between byte stream and character stream in Java

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.