Deep understanding of Java I/O Series II: Byte stream details

Source: Internet
Author: User

The concept of flow

The Java program completes the input/output through the stream. Flow is the abstraction of production or consumption information, and streams are linked to physical devices through Java input and output, although the physical devices they link to are not the same, and all streams behave in the same way. This means that an input stream can abstract many different types of input: from a disk file, from a keyboard, or from a network socket; Similarly, an output stream can be output to a console, a disk file, or a connected network.

In the input/output streams we normally touch, there is a concept that must be understood, what is input, what is output? The premise of this question is to know what the reference is, which is the program or memory . Input: Is the flow of data from the disk file or the outside of the network to the program or memory. The output is the opposite process. Where this "external" can be a lot of media:

1, local disk files, remote disk files.

2. Database link

3, TCP, UDP, HTTP network communication

4. Inter-process communication

5. Hardware equipment (keyboard, serial port)

Classification of streams

1, from the function: input stream, output stream

2, from the structure: byte stream, character stream

3. From Source: node stream, filter stream

One of the Inputstream/outputstream is designed for the byte stream, and Reader/writer is designed for character streams. Handles bytes or binary objects using a byte stream, processing characters or strings using a character stream.

At the bottom, all input/output is in bytes, and character-based streams provide a convenient and efficient way to process characters.

A node stream is a stream that reads and writes from a specific place, such as a disk or memory space, which is a direct docking target.

The filter stream is used as the input and output of the node stream, which is wrapped on the basis of the node flow and adds some specific functions.

InputStream

There is the color of the node flow, no color annotation for the filter stream, where FilterInputStream in the JDK is defined as: contains other input streams, which use these streams as their basic data source, can transfer data directly or provide some additional functionality, the class itself is not often used by us , which is commonly used for its subclasses.

An abstract class that defines the byte input pattern, which provides three overloaded read methods:

As we can see, three of the read methods, one of which is abstract. So here's the question: Why is only the first one abstract and the other two specific?

Because the first method is eventually called inside the next two methods, it is only necessary to rewrite the first method in the InputStream derived class. Here you can see that the first read method is related to a specific I/O device and requires subclasses to implement it.

The logical steps for reading and writing data are:

Open a Stream

While more information

Read/write Information

Close the stream

First, FileInputStream
1 public static void main (string[] args) throws IOException 2     {3         inputstream is  = new FileInputStream ("C:/tes T.txt "); 4         int length = 0; 5         byte[] buffer = new BYTE[20]; 6 while         ( -1! = (length = Is.read (buffer,0,20))) 7         {8
   
    string str = new String (buffer,0,length); 9             System.out.print (str);         }11         is.close ();     
   

Execution Result:

China Mobile base mi Goo read China Mobile base microphone music A

1, first we look at the contents of reading the file test:

2, here we use the input stream, reading is my native C drive in the name of the content in the test file.

3. The contents of each read are stored in buffer in this byte array, and then converted to string strings printed in the console.

4. Let's look at the 6th line of code: Because the content of a file is not known in advance, so it can be read in batches, up to 20 bytes at a time (that is, the length defined by the buffer array).

5, the function of length is to indicate that at the time of the last read, the length of the read is less than the length of the buffer array, while the loop body execution ends, the next time to read no more content, the Read method at this time will return-1, and then jump out of the loop.

6, for the operation of the flow, the last step is always to call the Close method, release resources.

Summary: the content in the text is deliberately defined as 41 bytes in length, and then printed with a newline. As you can see from the execution results, the first two reads are 20 bytes long, the third is 1 bytes, the last time no content returns-1, and then it jumps out of the loop body. Although this demo is very simple, but also is the most basic IO kind of need to master the part.

Second, FileOutputStream

This class is paired with FileInputStream and is similar in usage:

1 public static void main (string[] args) throws IOException2     {3         outputstream OS = new FileOutputStream ("C:/test1. TXT "); 4         String str =" China Mobile mobile phone reading "; 5         byte[] b = str.getbytes (); 6         Os.write (b); 7         os.close (); 8     }

Execution Result:

1. This demo mainly writes a string to a disk file.

2, in the 3rd line of the constructor to note, this method if the specified file does not exist, a new one will be created, if the specified file exists, the subsequent write operation will overwrite the original content.

This people will have such a question, if I do not want to overwrite the original content, just want to append the content later?

1 public static void main (string[] args) throws IOException2     {3         outputstream OS = new FileOutputStream ("c:/test.t XT ", True); 4         String str =" Registered user 600 million "; 5         byte[] b = str.getbytes (); 6         Os.write (b); 7         os.close (); 8     }

Execution Result:

1, from the execution results, this is appended to the original content; the only difference is the constructor of the third row.

OutputStream OS = new FileOutputStream ("C:/test.txt", true);

If the second argument is true , the byte is written to the end of the file, not to the beginning of the file.

Third, Bufferedoutputstream

In the FileOutputStream described earlier, is to read a byte in the program, write a byte out. In this case, frequently dealing with IO devices, I/O processing speed and CPU speed is not at all a magnitude (I/O is a physical device), in a lot of information, it is more consumption performance. Based on this problem, Java provides buffered byte streams through which applications can write individual bytes to the underlying output stream without having to call the underlying system for each byte write.

1 public static void main (string[] args) throws IOException2     {3         outputstream OS = new FileOutputStream ("c:/test.t XT "), 4         outputstream bs = new Bufferedoutputstream (OS), 5         byte[] buffer =" China Mobile reading Base ". GetBytes (); 6         Bs.write ( buffer); 7         bs.close (); 8         os.close (); 9     }

Execution Result:

Buffered output stream at the time of output, is not a byte-by-byte operation, but is written into the buffer area of memory first. The contents of the buffer are written to the target until the buffer is full or we call the Close method or the Flush method. Will not be transferred from memory to disk . Here's a look at what happens if you don't call the Close method:

1 public static void main (string[] args) throws IOException2     {3         outputstream OS = new FileOutputStream ("C:/test1 . txt "); 4         outputstream bs = new Bufferedoutputstream (OS); 5         byte[] buffer =" China Mobile reading Base ". GetBytes (); 6         Bs.write (buffer); 7//        bs.close (); 8//        os.close (); 9     }

Execution Result:

The Close method is not called here, which is equivalent to the contents of the buffer in memory. The bufferedoutputstream itself does not have a close method, and the Close method of the parent class Filteroutputstream is called:

1 public  void Close () throws IOException {2     try {3       flush (); 4     } catch (IOException ignored) {5     }6     Out.close (); 7     }

Here you can see that the essence of this method is to call the Flush method before closing the resource.

Flush is defined in the JDK as: refreshes this buffered output stream. This forces all buffered output bytes to be written out to the underlying output stream.

Iv. DataOutputStream

The data output stream allows the application to write the basic Java data type in an appropriate manner to the output stream. The application can then use the data input stream to read the data in.

1 public     static void Main (string[] args) throws IOException 2     {3         dataoutputstream dos = new DataOutputStream ( New Bufferedoutputstream (4                 new FileOutputStream ("C:/data.txt")); 5         byte B = 4; 6         char c = ' C '; 7         int i = n; 8         float f = 3.3f; 9         dos.writebyte (b);         Dos.writ Echar (c);         dos.writeint (i);         dos.writefloat (f);         dos.close ();

Execution Result:

After opening, the inside is garbled, the program is written after a binary file. Our program writes the basic data type of Java to the text, note that this is not a string, but a basic data type. It makes no sense for us to write like this, and we're going to read it the same way.

1         dataoutputstream dos = new DataOutputStream (New Bufferedoutputstream (2                 new FileOutputStream ("C:/data.txt") )); 3         byte B = 4; 4         char c = ' C '; 5         int i = n; 6         float f = 3.3f; 7         dos.writebyte (b); 8         Dos.writechar ( c); 9         Dos.writeint (i);         dos.writefloat (f);         dos.close ();         datainputstream dis = new DataInputStream (Bufferedinputstream                 new FileInputStream ("C:/data.txt"));         Dis.readbyte ()); System.out.println (Dis.readchar ());         System.out.println (Dis.readint ()         ); System.out.println (Dis.readfloat ());         Dis.close (); 20     

Execution Result:

4c123.3

As we see here, our data input stream allows the application to read the basic Java data types from the underlying input stream in a machine-independent manner.

In particular, it is important to note that the order in which data types are read is consistent with the order in which they were written, otherwise garbled or read information is inaccurate.

This is why we can understand that: when writing is different types of basic data, different basic data types of byte length is not the same, if the order of the reading time is inconsistent, it will cause the combination of the byte confusion, resulting in garbled characters or go to righteousness.

Deep understanding of Java I/O Series II: Byte stream details

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.