Conceptual understanding of Java IO flow

Source: Internet
Author: User
Tags garbage collection
1.Java IO Flow concept, classification, class diagram. The concept of 1.1 Java IO stream

Java IO is the basis of input and output, can easily realize the data input and output operation. In Java, a different input/output source (keyboard, file, network connection, etc.) is abstracted as "stream". The flow allows Java programs to access different input/output sources in the same way. Stram is ordered data from the origin (source) to the received (sink).

Note: Java puts all the traditional stream types under the Java IO Package for input and output functions. Classification of 1.2 IO streams:

According to the different classification methods, the flow can be divided into different types. There are three kinds of commonly used classifications: 1.2.1 According to the flow direction, can be divided into input and output streams. input stream: Data can only be read from, not written to. Output stream: Data can only be written to and not read to.

The input here, the output involves a direction of the problem, as shown in Figure 15.1 of the data flow, data from memory to the hard disk, often referred to as the output stream-that is, the input here, the output is from the point of view of the memory where the program runs.

Note: The data stream shown in Figure 15.1 should be an input stream if viewed from the perspective of the hard disk, but the input/output stream is partitioned from the point of view of the memory where the program is running, so the output stream is the same as the stream in Figure 15.1. Rather than an input stream.

For the data flow shown in Figure 15.2, data flows from the server to the client over the network, in which case the server-side memory is responsible for outputting the data to the network, so the server-side program uses the output stream; The client-side memory is responsible for reading data from the network. Therefore, the client-side program should use an input stream.

Note: Java input stream is mainly inputstream and reader as base class, and output stream is mainly by OutputStream and writer as base class. They are abstract base classes and cannot be created directly. The 1.2.2 can be divided into byte stream and character streams according to the Operation unit.

The use of byte streams and characters is almost complete, and the difference is that the byte stream operates on a different unit of data than the character stream, which is the 8-bit bytes of the data unit, and the character streams operate with a data unit of 16 bits.

The byte stream is mainly composed of InputStream and OutputStream as base classes, while character streams are mainly reader and writer as base classes. 1.2.3 is divided into node flow and processing flow according to the role of the stream.

A stream of data that can be read/written from/to a particular IO device (such as a disk, network), called a node stream. A node stream is also called a low-level stream. Figure 15.3 shows a diagram of the node flow.
As you can see from figure 15.3, when you use a node stream for input and output, the program connects directly to the actual data source and to the actual input/output node.
The processing stream is used to connect and encapsulate an existing stream, and to implement the read/write function of the data through the encapsulated stream. Processing streams are also called advanced streams. Figure 15.4 shows a schematic diagram of the process flow.

as you can see from figure 15.4, when you use a processing stream for input/output, the program is not directly connected to the actual data source, and does not connect to the actual input and output nodes. One obvious benefit of using a process flow is that, as long as the same processing flow is used, the program can access the different data sources using exactly the same input/output code, and the data source that the program actually accesses will change as the flow of the nodes in the processing stream is changed. 1.3 Flow principle analysis and common flow classification table: 1.3.1 Flow principle Analysis:

Java IO streams involve more than 40 classes, which look messy, but are actually very regular and have very close links to each other, and more than 40 classes of Java IO streams are derived from the following 4 abstract class base classes. Inputstream/reader: The base class for all input streams, the former is the byte input stream, the latter is the character input stream. Outputstream/writer: The base class for all output streams, the former is the byte output stream, and the latter is the character output stream.

For InputStream and reader, they abstract input devices into a "water pipe," each of which "drops" of water in order, as shown in Figure 15.5:
As you can see from figure 15.5, the byte stream and character streams are handled in a very similar way, except that they handle different input/output units. The input stream uses an implicit record pointer to indicate which "drip" is currently being prepared to be read, and whenever the program extracts one or more "drops" from the InputStream or reader, the record pointer moves backwards; Both InputStream and reader provide methods to control the movement of record pointers.

For OutputStream and writer, they also abstract the output device into a "pipe", except that there are no water droplets in the pipe, as shown in Figure 15.6:

As shown in Figure 15.6, when the output is executed, the program is equivalent to the "water droplets" into the output flow of the pipe, the output stream also uses an implicit pointer to identify the current drop in the position, whenever the program to OutputStream or writer inside the output of one or more droplets, The record pointer moves backwards automatically.
In addition to the basic conceptual model of Java IO, figure 15.5 and Figure 15.6 Show the flexibility of Java input and output flow design in Java's processing flow model. The function of processing flow is mainly embodied in the following two aspects. Performance improvement: Provides input and output efficiencies primarily in a way that increases buffering. Easy to operate: The process flow may provide a series of convenient ways to input and output a large amount of content at a time, rather than input/output one or more "water droplets."

The processing stream can be "grafted" on any existing stream, which allows the Java application to use the same code, transparently, to access the data flow of different input and output devices. Figure 15.7 shows the model of the process flow.

1.3.2 Java input/output stream system common flow classification table

Classification byte input stream byte output stream character input stream character output stream
Abstract base class InputStream OutputStream Reader Writer
accessing files FileInputStream FileOutputStream FileReader FileWriter
accessing arrays Bytearrayinputstream Bytearrayoutputstream CharArrayReader Chararraywriter
Access pipeline PipedInputStream PipedOutputStream Pipedreader PipedWriter
Access string StringReader StringWriter
Buffer stream Bufferedinputstream Bufferedoutputstream BufferedReader BufferedWriter
Convert stream InputStreamReader OutputStreamWriter
Object Stream ObjectInputStream ObjectOutputStream
Abstract base class FilterInputStream Filteroutputstream FilterReader Filterwriter
Print Flow PrintStream PrintWriter
Push back the input stream Pushbackinputstream Pushbackreader
Special flow DataInputStream DataOutputStream

Note: The class that is marked in bold in the table represents the node stream and must be directly associated with the specified physical node: A class that is marked in italics represents an abstract base class and cannot be created directly. 2. Usage of commonly used IO streams

The following are the features and usage of the commonly used IO streams, and only the characteristics and methods of each IO stream are clear. In order to choose the corresponding IO flow in front of different requirements. 2.1 IO System base class (Inputstream/reader,outputstream/writer).

The operation of the byte stream and character streams is basically the same, but the operation of the data unit is different--the operation unit of the word stream is bytes, and the operation unit of character streams is the characters. So the byte stream and character streams are sorted together.

InputStream and reader are abstract base classes for all input streams, and cannot create instances to perform input, but they will become templates for all input streams, so they are methods that all input streams can use.
The following 3 methods are included in the InputStream. int read (); Reads a single byte from the input stream (equivalent to taking a drop of water from the pipe shown in Figure 15.5), returning the byte data that is read (byte data can be directly converted to type int). int read (byte[] b) reads up to b.length bytes of data from the input stream and stores it in byte array B, returning the number of bytes actually read. int read (byte[] b,int off,int len); Reads up to Len bytes of data from the input stream and stores it in array B, in array B, not starting from the beginning of the array, but starting at the off position, returning the number of bytes actually read.

The following 3 methods are included in the reader. int read (); Reads a single character from the input stream (equivalent to taking a drop of water from the pipe shown in Figure 15.5), returning the character data that is read (byte data can be directly converted to type int). int read (char[] b) reads up to b.length characters from the input stream and stores them in byte array B, returning the number of characters actually read.

int read (char[] b,int off,int len); Reads up to Len character data from the input stream and stores it in array B, in array B, not starting from the beginning of the array, but starting at the off position, returning the number of characters actually read.

Comparing the methods provided by InputStream and reader, it is not difficult to find that the functions of these two base classes are basically the same. Both InputStream and reader abstract the input data into the water pipe shown in Figure 15.5, so the program can read a "droplet" every time through the read () method, or through Read (char[] chuf) or read (byte[) b) method to read multiple "droplets". When using an array as an argument in the Read () method, we can understand that using a "bamboo tube" to fetch water in a water pipe as shown in Figure 15.5, as shown in Fig. 15.8, the parameters of the read (char[] cbuf) method can be understood as a "bamboo", each time the program calls the input stream read (char [] cbuf) or read (byte[] b) method, it is equivalent to using "bamboo" from the input stream to take out a tube of "water droplets", the program gets "bamboo" inside of "water droplets", converted into the corresponding data can be, the program repeated the "fetching" process, until the end. How does the procedure judge the final intake of water? Until read (char[] chuf) or read (byte[] b) method returns-1, which indicates the end point of the input stream.

InputStream and reader provide some way to move the pointer: void mark (int readaheadlimit); Record a mark (Mark) at the current position of the record pointer. Boolean marksupported (); Determines whether this input stream supports the mark () operation, that is, whether the record tag is supported. void Reset (); Reposition the record pointer for this stream to the location of the last record mark (Mark). Long Skip (long n); The record pointer moves n bytes/characters forward.

OutputStream and Writer:
OutputStream and writer are also very similar in that they use the model shown in Figure 15.6 to perform input, and two streams provide the following three methods: void write (int c); Outputs the specified byte/character to the output stream, where c can represent a byte, or it can represent a character. void Write (byte[]/char[] buf); Outputs the data in a byte array/character array to the specified output stream. void Write (byte[]/char[] buf, int off,int len); Outputs a byte/character array that starts at the off position, and the length len is in the output stream.

Because the character stream acts directly as an operating unit of characters, writer can use a string instead of a character array, which is a string object as an argument. The writer also contains the following two methods. void write (String str); Outputs the characters contained in the STR string to the specified output stream. void Write (String str, int off, int len); The character in the STR string that starts at the off position, and the length Len, is exported to the specified output stream. use of base-class file streams for 2.2 IO systems (Fileinputstream/filereader, Fileoutputstream/filewriter)

As mentioned earlier, InputStream and reader are abstract classes that cannot create instances themselves, but they have a single input stream for reading files: FileInputStream and FileReader, both of which are node streams-directly associated with the specified file. The following program demonstrates the use of FileInputStream and FileReader.
To read a file using FileInputStream:

public class MyClass {
  public  static void Main (string[] args) throws ioexception{FileInputStream
      ;
      try {
          //create byte input stream
          fis=new fileinputstream ("e:\\learnproject\\iotest\\lib\\src\\main\\java\\com\\ Test.txt ");
          Create a 1024-length bamboo
          byte[] b=new byte[1024];
          The actual number of bytes used to save
          int hasread=0;
          Use a loop to repeat the process while
          ((Hasread=fis.read (b)) >0) {
              //Remove the droplets in the Bamboo tube (bytes), convert the byte array to a string for output
            System.out.print (New String (B,0,hasread));
          }
      catch (IOException e) {
        e.printstacktrace ();
      } finally {
          fis.close ();}}}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22

Note: The above program finally uses the Fis.close () to turn off the input stream of the file, like JDBC programming, open the file IO resources in the program does not belong to the memory resources, garbage collection mechanism can not reclaim the resource, so should be shown to close the open IO resource. Java 7 Rewrites all IO resource classes, all of which implement the Antocloseable interface, so all of these IO streams can be closed by automatically closing the resource's try statement.

To read a file using FileReader:

public class Filereadertest {
    public  static void Main (string[] args) throws ioexception{FileReader fis=
        null;
        try {
            //create byte input stream
            fis=new filereader ("E:\\learnproject\\iotest\\lib\\src\\main\\java\\com\\test.txt");
            Create a 1024-length bamboo
            char[] b=new char[1024];
            The actual number of bytes used to save
            int hasread=0;
            Use a loop to repeat the process while
            ((Hasread=fis.read (b)) >0) {
                //Remove the droplets in the Bamboo tube (bytes), convert the byte array to a string for output
                System.out.print (New String (B,0,hasread));
            }
        catch (IOException e) {
            e.printstacktrace ();
        } finally {
            fis.close ();}}}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18
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.