Java I/O processing, apiio

Source: Internet
Author: User

Java I/O processing, apiio

IO is short for input and output. In actual use, input and output are oriented. Just as in reality, two people borrow money from each other. For example, A borrows money from B, which is borrowed from A, and B. Therefore, when talking about input and output in a program, you also need to clearly distinguish the relative content.

In the program, both input and output are relative to the current program. For example, reading the content of a configuration file from the hard disk to the program is equivalent to inputting the content of the file into the program, therefore, the input and "read" pairs, and the content stored in the program to the hard disk, is equivalent to outputting the content of the file to the outside of the program, so the output corresponds to "write. Familiarizing yourself with the ing between input and output will help you learn the subsequent content.

 

In Java, the concept of input and output is much more extensive than that of input and output in other languages, including not only reading and writing files, but also sending network data, i/O can even read/write memory data and receive console data.

In order to make the input and output structures uniform and facilitate programmers to use IO-related classes, a new concept-Stream (Stream) was introduced in the IO class design of Java ).

 

Many types of operations are required during I/O operations, such as files, memory, and network connections. These operations are called data sources ), different data sources are processed in different ways. If the data is directly handed over to the programmer for processing, it is complicated for the programmer. Therefore, when reading data in all I/O classes, JDK API converts the data from the data source to a fixed data sequence. When writing data, write the data to the data sequence in a certain format. The jdk api writes the data in the data sequence to the corresponding data source. In this way, the system completes complex data conversion and different transformations between different data sources, thus simplifying coding for programmers.

I/O's design is the same as the water supply and drainage system design in the city. When water is supplied, different types of water sources include river water, lake water, and groundwater, the water supply company converts the water source to the corresponding water flow. In the design of the drainage system, you only need to discharge the sewage into the sewage pipeline. As to how the sewage is processed, you do not need to care about it. This simplifies the treatment of domestic water.

In IO design, this data sequence is called Stream ). By using the concept of stream, programmers only need to establish different streams for different data sources, and the complexity of implementation of the bottom layer is completed by the system, so that programmers do not have to have a deep understanding of the read and write methods for each data source, thus reducing the complexity of IO programming.

During the entire IO process, the data reading process is divided into two steps:

1. Convert the content of the data source to a stream structure. This step is completed by jdk api. Programmers only need to select the appropriate stream type.

2. read data from the stream. This step is completed by the programmer. The data sequence in the stream is consistent with the data storage sequence in the data source.

The data writing process is divided into two steps:

1. A special stream structure established to connect to the specified data source. This step is completed by jdk api. Programmers only need to select the appropriate stream type.

2. Write Data to the stream in a certain format. This step is completed by the programmer. The data in the stream is stored in the data source order.

Finally, when the data is written to the stream, you can write the data in the stream to the data source in a certain way, or when the stream is closed, the system will automatically write the data in the stream to the data source.

 

In this way, the most complex and data source operations are completed by the jdk api during the entire IO class design. When programmers program, they only need to select the appropriate stream type, then read and write. Like the actual structure, the Stream in IO is also oriented. The Stream used for reading is called the Input Stream, and the Stream used for writing is called the Output Stream ). When reading and writing, you need to select the appropriate stream object for operation.

Because Java uses object-oriented technology, each stream type is represented by a special class during implementation, and the logic of reading or writing data sources of this type is encapsulated inside the class, when a programmer creates a corresponding object, the stream structure is completed. Subsequent IO operations only need to read or write the internal data of the stream object. In this way, IO operations are relatively simple and easy for Java programmers.

 

 

I/O system

In JDK APIs, the basic IO classes are located in java. io package, while the newly implemented IO class is located in a series of java. in the package name starting with nio, java is introduced first. the architecture of classes in the io package.

According to the preceding description, the stream has a direction. The structure of the whole stream can be divided into two types based on the direction of the stream:

 

1. input stream:

This type of stream converts data from an external data source to a stream. By reading data from this type of stream, the program reads data from an external data source.

 

2. output stream:

This type of stream converts the data in the stream to the corresponding data source. By writing data to this type of stream, the program writes the data to the corresponding external data source.

In actual implementation, due to the history of JDK APIs, two types of streams are implemented in the java. io package: byte stream and char stream ). The two streams implement the unit of data sequence in the stream. In the byte stream, the data sequence is measured in bytes, that is to say, the data in the stream is converted into streams in the order of one byte and one byte. The basic unit for such stream operations is a byte. For byte streams, the data sequence is in char units, that is to say, the data in the stream is converted into a stream according to the insert sequence of a char. The basic unit for this type of stream operation is a char.

In addition, the byte stream is added to the API from JDK1.0, while the bytes stream is added to the API from JDK1.1. For the JDK version currently used, both streams are included in the API. In actual use, the efficiency of the merge stream is higher than that of the word throttling.

In actual use, the classes in the upstream stream basically correspond to those in the byte stream. Therefore, when learning the IO class, you can start learning from the most basic byte stream.

When SUN designs jdk I/O classes, a parent class is designed for each series of classes according to the above classification, and classes that implement specific operations are used as subclasses of these classes, the parent classes of each system in the four systems of the IO class design are:

 

InputStream

This class is the parent class of all byte input streams in IO programming. Familiarity with this class will greatly help you to use byte input streams. The following describes in detail.

According to the concept of the preceding stream, the byte input stream constructs the structure of the input stream for reading data in byte form. Each object of this class is an actual input stream, during the construction, the API completes the operation to convert the external data source to the stream object, which is transparent to the programmer. When using a program, the programmer only needs to read the stream object to read external data.

InputStream is the parent class of all byte input streams. Therefore, every method contained in the InputStream class will be inherited by all byte input stream classes, by declaring the basic methods for reading and operating data in the InputStream class, each subclass overwrites the corresponding method as needed, this design ensures that each byte input stream subclass is consistent with the functional methods available to programmers during actual use. This will simplify the difficulty of I/O learning and help programmers program the program.

By default, the internal data of the input stream is read in one way, that is, the data can only be read from the input stream before and after, and the data that has been read will be deleted from the input stream. If you need to read the same part of the stream repeatedly, you must mark it using the mark method in the stream class before reading it again. This design requires profound experience when using stream classes.

 

In the InputStream class, common methods include:

 

A. available Method

 

Public int available () throws IOException

This method returns the number of bytes not read in the current stream object. That is, to obtain the length of the data in the stream.

Assume that there are 100 bytes of data in the first flow. If the program calls the corresponding method to read one byte, the number of remaining bytes in the current stream will become 99.

In addition, this method is not correctly implemented in all byte input streams, so using this method to obtain the number of data in the stream is unreliable.

 

B. close Method

 

Public void close () throws IOException

This method is used to close the current stream object and release the resources occupied by the stream object.

After the I/O operation is complete, closing the stream is a function that needs to be implemented during I/O operations. This ensures data source security and reduces memory usage.

 

C. markSupported Method

 

Public boolean markSupported ()

This method is used to determine whether a stream supports marking ). Marking is similar to a bookmarked during reading, so you can easily go back to the original position and continue reading down.

 

D. reset Method

Public void reset () throws IOException

This method is used to return the stream reading position to the set mark position. You can continue to read backward from this position.

 

E. mark Method

Public void mark (int readlimit)

Set a flag for the current position in the stream so that you can continue reading from this position in the future. The readlimit variable indicates the maximum number of data records in the stream that can be read after this flag is set. When the flag is set, the number of bytes read exceeds this limit, and the flag becomes invalid.

 

F. read Method

The read method is the core method used by the input stream class. If you are familiar with this method, it indicates that I/O is basically used. Therefore, you must have a deep understanding of the use of this method in your learning and later use.

When actually reading data in a stream, the data can only be read in sequence according to the data storage sequence in the stream. When using a byte input stream, the minimum unit for reading data is byte ).

In addition, it should be noted that the read method is a blocking method, that is, if no data in the stream object can be read, The read method will prevent the program from running down, until data can be read.

There are three read methods in total, which are:

 

Public abstract int read () throws IOException

This method is used to read the first byte of the current stream object. When this byte is read, it will be deleted from the stream object. The second byte in the original stream object will become the first byte in the stream, the value obtained using the available method of the stream object is also reduced by 1. To read the data in the stream, you only need to read each data in one loop. When the stream is read to the end, this method returns-1. Only the last byte of the int returned value is valid data in the stream. Therefore, force conversion is required to obtain the value in the stream. The purpose of converting the returned value to int is to solve the-1 problem.

This method is abstract, so it will be overwritten in the subclass to implement the most basic data reading function.

 

Public int read (byte [] B) throws IOException

The function of this method is to read data from the current stream object and store the read data to array B in sequence (B needs to be initialized in advance, that is, data of the first byte in the current stream is stored to B [0], data of the second byte is stored to B [1], and so on. Data that has been read in the stream will also be deleted, and subsequent data will become the first byte in the stream. The actual number of bytes read is returned as the return value of the method.

 

Public int read (byte [] B, int off, int len) throws IOException

This method is similar to the preceding method. It also stores the read data in B, but stores the first data in the stream to the left-down position in B, A maximum of len data can be read, and the actual number of bytes read is returned as the return value of the method.

 

G, skip Method

Public long skip (long n) throws IOException

This method skips n Bytes of the current stream object, and returns the number of bytes actually skipped in the return value.

After n Bytes are skipped, if you want to read the data, the data is read from the new location. By using this method, you can skip the specified number of bytes in the overcurrent without reading them in sequence.

After the data is read from the stream, a byte array is obtained. You need to parse the byte array based on the previous data format.

Because the InputStream class is the parent class of the byte input stream, each subclass in this system contains the above methods, which are the basis for reading IO stream data.

 

Byte output stream OutputStream

This class is the parent class of all the byte output streams. In actual use, the subclass of this class is generally used for programming, but the internal method of this class is the basis for realizing the byte output stream.

The classes in this system write the corresponding data to the data source. When writing data, the operations are implemented in two steps: Step 1: Write the data to be output to the stream object, the data format is set by the programmer. This step requires code implementation. Step 2: output the data in the stream to the data source. This step is implemented by the API, programmers do not need to understand the internal implementation details. They only need to construct the corresponding Stream object.

When a stream is actually written, the stream retains a buffer, saving the data written to the stream object by the programmer first, and then outputting the data to the data source when the buffer is full. Of course, when the stream is closed, the data in the output stream is forcibly output.

The unit of data in the byte output stream is byte. When writing data into the stream, data needs to be converted to a byte array for writing.

 

In OutputStream, common methods include:

A. close Method

Public void close () throws IOException

This method is used to close the stream and release the resources occupied by the stream.

 

B. flush Method

Public void flush () throws IOException

This method forcibly outputs the buffered data in the current stream object. This method can be used to achieve immediate output.

 

C. write Method

The write method is the core method in the output stream. This method writes data to the stream. Before writing data, you must implement the corresponding format and write the data to the stream in sequence. The writing sequence is the actual data output sequence.

There are three write methods in total, which are:

Public abstract void write (int B) throws IOException

This method writes a byte of data to the end of the stream. The written data is the last byte of parameter B. When writing data to a stream, write data in the logical order. This method is implemented in the subclass of OutputStream.

Public void write (byte [] B) throws IOException

This method writes the data in array B to the current stream object in sequence.

Public void write (byte [] B, int off, int len) throws IOException

The function of this method is to write the data from array B starting from the subscript is off (inclusive), and the subsequent data with a length of len into the stream object in sequence.

When writing data, you also need to set the format of the byte value based on the logic requirements. Different formats are implemented based on different requirements.

 

Character input stream Reader

The character input stream system is an upgrade to the byte input stream system. The sub-class function basically corresponds to the sub-class in the byte input stream system. However, the internal design of the character input stream is different, in this way, the execution efficiency of Character Input streams is higher than that of byte input streams. in the case of similar functions, You can prioritize the use of classes in the character input stream system to improve the program execution efficiency.

The classes in the Reader system are functionally consistent with those in the InputStream system. The biggest difference is that the unit for reading data by classes in the Reader system is char ), that is to say, each time you read data with at least one character (two bytes), the Data Reading method in the Reader system uses the character as the most basic unit.

There are many methods in the Reader class and InputStream class, both declared and functional, but two methods are added, which are described in sequence as follows:

 

A. read Method

Public int read (CharBuffer target) throws IOException

The function of this method is to read the data in the stream into the CharBuffer object in sequence, and the actual number of char read is returned as the return value.

 

B. ready Method

Public boolean ready () throws IOException

This method is used to return whether the current stream object is ready, that is, whether the stream contains data that can be read.

 

For other methods similar to the InputStream class, refer to the above introduction.

 

 

Character output stream Writer

The character output stream system is an upgrade to the byte output stream system. The sub-class function basically corresponds to the byte output stream. However, because the class design in this system is relatively late, the class execution efficiency in this system is higher than the class efficiency in the byte output stream. In the case of similar functions, you can use the classes in this system first to improve the program execution efficiency.

The classes in the Writer system are functionally consistent with those in the OutputStream system. The biggest difference is that the unit of data written by the classes in the Writer system is char ), that is to say, each time data with at least one character (two bytes) is written, the Data Writing Method in the Writer system uses the character as the most basic operating unit.

Many methods in the Writer class and OutputStream class are the same in both declaration and function, but some methods are added, which are described in sequence as follows:

 

A. append Method

Write Data to the end of the stream. There are three methods in total, which are:

Public Writer append (char c) throws IOException

The function of this method is exactly the same as that of write (int c), that is, writing character c to the end of the stream.

Public Writer append (CharSequence csq) throws IOException

This method is used to write the CharSequence object csq to the end of the stream. When writing, it calls the toString method of csq to convert the object to a string, and then writes the string to the end of the stream.

Public Writer append (CharSequence csq, int start, int end) throws IOException

This method is similar to the preceding method. It only writes the converted string from the index value to start (inclusive) to the end (excluded) part of the index value to the stream.

 

B. write Method

In addition to the basic write method, two new methods are added to the Writer class, which are:

Public void write (String str) throws IOException

The function of this method is to write the string str into the stream. During writing, str is first converted to the corresponding char array using the getChars method, and then written to the end of the stream in sequence.

Public void write (String str, int off, int len) throws IOException

The function of this method is to set the index value in the string 'str' to off (inclusive) and write the subsequent len characters to the end of the stream.

Using these two methods makes it easier to write strings to the end of the stream.

For other methods similar to the OutputStream class, refer to the above introduction.

 

Summary

When I/O classes are used, the classes in the corresponding system are selected for actual use based on the logic needs to implement IO-related functions in the program.

After being familiar with the I/O class system, you can first familiarize yourself with the use of basic I/O classes, and then gradually learn about the use of related classes in the I/O class system, thus gradually become familiar with java. use classes in the io package, and then master IO programming.

In actual use, the corresponding sub-classes of these four classes are generally used, and each sub-class completes related functions. For these subclasses, you can also classify these IO classes:

1. Object stream

I/O Stream class that directly connects to the data source

2. Decorative stream

A data source is built on other object stream objects instead of directly connecting to the data source.

 

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.