Getting Started with Java: Getting Started with Java IO overview

Source: Internet
Author: User

I/O problems are unavoidable in any programming language, so I/O problem is the core problem of the whole human-computer interaction, because I/O is the main channel for the machine to acquire and exchange information. In today's data explosion era, I/O issues are particularly prominent and can easily become a performance bottleneck.

The purpose of this article is to analyze the intrinsic working mechanism of I/O and the basic architecture of the Java I/O class Library to help beginners understand Java I/O in general. The use of specific various I/O class libraries, readers in the face of practical problems, combined with the explanation of this article to understand the master.

1. Is the I/O

Describing the I/O mechanism of Java, we use the example of pumping from a river to explain the process of reading a file.

To pull the river out, first we need a pump and then throw the pump into the river. Here, the river is the equivalent of a file, and we need to build a pump and link the pump to the river:

New FileInputStream ("E:/rivier.txt");

FIS is the pump, E:/rivier.txt is the river.

Equipment ready, you can open the tap to get water, but the water to be stored, so the second step, we also need to have a water container:

byte New byte [10];

The container bottle is an array of type Byte, with a size of 10. The container is defined as a byte array and not as an array type, because the pump we use is very special, and the smallest unit of water to be pumped is a byte (you should take 1 drops to understand it).

Next, put the container under the faucet, turn on the faucet, and start pumping the water into the container.

Fis.read (bottle);

This allows the pump to take out 10 drops of water (10 bytes) into the bottle container. Then the data in the bottle can be arbitrarily disposed of by us.

Java provides us with two types of pumps, the first type of pump is called Xxxinputstream, its pumping unit is bytes, of course, the container of water is naturally a byte array byte[].

The second type of pump is called Xxxreader, which is a unit of characters, and a water container is a character array char[].

In other words, if we use the first pump to Xxxinputstream, we draw a byte, and if we use the second pump xxxreader, it is char. (For the difference between byte byte and char, own brain complement ...) )

The xxx here says that the water pumped is the river, or the lake, seawater, sewage ..., that is, XXX represents the source of the data. such as fileInputStream, indicates that the pump is specifically read from the file data,ByteArrayinputstream, is specifically from the character array is in memory read data.

To summarize, to read a file, proceed as follows:

1. Instantiate a Xxxinputstream object (select a pump, specify the water source)

2. Identify the object that receives the data (prepare the container)

3. Read () (Turn on the tap)

Now, through the pumps above, users can get water from a variety of places, according to the size of the quilt. But the user felt that the pump function is still weak point, if the tap is turned on, is hot, hot coffee is good!

Obviously the pump has been unable to, if the heating, cooking coffee function design into the pump inside, then the pump will appear too complex, but also increased the difficulty of maintenance when the failure.

So, let's take a different train of thought, under the tap of the pump, and then a heating tube:

New FileInputStream ("E:/yellow_river.txt"); // get the pump ready. New ObjectInputStream (FIS); // Add a heater

In this way, you can get hot water just by calling the faucet of the heating tube:

Ois.readdouble ();//read out is a double type of data, is no longer a byte data (that is, the extraction of hot water)

So, in general, reading files in Java is like pumping, first of all, you need to select the right pump according to the Reading unit , according to the reading source . If necessary, you can also add tubes after the pump to enhance the function.

Please try to describe the mechanism of writing files according to the example of drainage.

2. Example understanding

Now let's combine the examples above to understand a few examples.

1) Read files by byte FileInputStream

FileInputStream FIS =NewFileInputStream ("E:/in.txt");//creating an input stream object (pump) while(fis.available () > 0) {       byte[] B =New byte[10];//Create an array (water container)    intNresult = Fis.read (b);//when reading data into an array, and reading the data, Nresult is assigned an integer of >-1, which indicates how many bytes were actually read    if(Nresult = =-1)//the data in the file is read, no data is readable.         Break; System.out.println (NewString (b));      } fis.close (); //After reading the data, the pump needs to be switched off

2) Read the file FileReader by character:

FileReader Rdfile =NewFileReader ("E:/in.txt");//instantiate file input stream object (pump) while(Rdfile.ready ()) {//whether the input stream is ready to read (the pump is ready to pump water) .    Char[] ChIn =New Char[10];//Preparing the container    intNresult = Rdfile.read (chIn);//Read Data    if(Nresult = =-1)//If you do not read the data、 Break;   System.out.println (ChIn);  } rdfile.close (); //stop pumping, turn off the pump.

FileReader satisfies the xxxreader naming rule, from which the name can be judged to read the data by character, and the data source is the file.

3. Read with buffer

Or use the pumping example to explain what a buffer is. When we use water, there are two ways to do it, one is to turn on the faucet and wait for it to fill the container with water each time. The second method is that the home has a large water tank, the first to fill the big tank, each time with the use, go directly to the tank to take. When someone in the tank is not enough, turn on the faucet and fill the tank.

It is obvious that the second method is highly efficient, regardless of the effect of long water storage time on deterioration.

Files are usually placed in devices such as disks, which are faster to read and write faster than memory. The above FileInputStream or filereader each time the read () method is executed, it will go to the hard disk to read once. If the data in the file in advance read a certain size into memory, and each time read (), from the memory of reading, will reduce the hard disk read and write times, much higher efficiency. If the data in this memory is not enough, then go to the hard disk to continue reading the data to fill up the memory, and then continue to use this block of memory. This memory is the buffer.

Usage examples:

New FileReader ("E:/in.txt"new  BufferedReader (rdfile);  Creates a BufferedReader object String strLine;     while NULL ) {       System.out.println (strLine);}   Brdfile.close ();   

Example, rdfile this FileReader object wrapped in BufferedReader object brdfile, directly manipulate the Brdfile object, you can implement the buffering function of the read operation.

Similarly, read by byte can use the Bufferedinputstream class to wrap the Inputsteam.

4. I/O architecture

Now that we've learned about Java I/O systems and learned some simple I/O operations, let's turn to Java DOC and see how Sun is designing I/O systems through object-oriented thinking.

To summarize:

1.InputStream and OutputStream are abstract classes that read and write data by Byte, and are the base class for all byte input and output streams.

2. Reader and writer are abstract classes that read and write data by character, and are the base class for all character input and output streams.

3. Inheriting them is a "pump" or "drain" for a specific data source, providing a basic implementation of read and write.

4. The construction method generally needs to provide a data source.

Getting Started with Java: Getting Started with Java IO overview

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.