Java I/O system character stream

IO stream: used to process data on the device.

            Equipment: hard disk, memory, keyboard entry.

 

IO has specific categories:

    1: Byte stream and character stream depending on the type of data processed.

    2: According to different flow directions, input flow and output flow.

 

Origin of character stream:

    Because of different file encodings, there are character stream objects that operate efficiently on characters.

    Principle: In fact, when reading bytes based on the byte stream, check the specified code table.

 

The difference between byte stream and character stream:

    1: When a byte stream is read, a byte is returned when a byte is read.

         The character stream uses the byte stream to read one or more bytes (the number of bytes corresponding to Chinese is two, and it is 3 bytes in the UTF-8 code table). Check the specified encoding table first, and return the found characters.

    2: Byte stream can handle all types of data, such as pictures, mp3, avi.

         The character stream can only handle character data.

Conclusion: As long as it is dealing with plain text data, it is necessary to give priority to the use of character streams. Other than that, byte streams are used.

 

IO system. There are two basic functions: read and write.

    1: byte stream

        InputStream (read), OutputStream (write).

    2: character stream

        Reader (read), Writer (write).

 

 

Basic read and write operations:

        Because data usually exists in the form of files.

        Therefore, it is necessary to find stream objects in the IO system that can be used to manipulate files.

        The object is easier to obtain by name.

        Because most of the subclass name suffixes in the IO system are the parent class name. The prefix is ​​the name that reflects the function of the subclass.

 

        Reader

                InputStreamReader

                        FileReader: A character-reading stream object specialized for processing files.

        Writer

                OutputStreamWriter

                        FileWriter: A character write stream object specialized for processing files.

 

        Common methods in Reader:

                1:int  read():

                        Read a character. What is returned is the character that was read. Returns -1 if the end of the stream is read.

                2:int read(char[]):

                        Store the read characters in the specified array, and return the number of characters read, that is, the number of elements loaded into the array. Returns -1 if the end of the stream is read.

                3:close():

                        Reading characters actually uses the function of the window system, and it is hoped that the resources will be released after use.

 

        Common methods in Writer:

                1: write(ch): Write a character to the stream.

                2: write(char[]): Writes an array of characters to the stream.

                3: write(String): Write a string to the stream.

                4: flush(): refresh the stream, flush the data in the stream to the destination, and the stream still exists.

                5: close(): Close the resource: flush() will be called before closing to refresh the data in the stream to the destination. Then the stream is closed.

        

        FileWriter:

                This class has no specific methods. Only its own constructor.

                This type of feature is that,

                1: For processing text files.

                2: There is a default encoding table in this class,

                3: There is a temporary buffer in this class.

    

                Constructor: When writing to a stream object initialization, there must be a destination for storing data.

                FileWriter(String filename):

                What does this constructor do?

                1: Call system resources.

                2: At the specified location, create a file.

                        Note: If the file already exists, it will be overwritten.

                FileWriter(String filename,boolean append):

                        This constructor: When the value of the boolean type passed in is true, the data will be continued at the end of the specified file.

 

 

        FileReader:

                1: Stream object for reading text files.

                2: Used to associate text files.

                

                Constructor: When initializing the read stream object, you must specify a read file.

                            FileNotFoundException occurs if the file does not exist.

                FileReader(String filename);

        

        Listing 1:

        1: Store text data into a file.

            

            Constructors that read or write stream objects, as well as read and write methods, and flush close functions throw IOException or its subclasses.

 

            So it has to be dealt with. Or throws throw, or try catch processing.

 

            Listing 2:

            Complete exception handling method.

            

 

 

 

            Listing 3:

            Read an existing text file and print the text data.

            

             It is not efficient to read one character at a time and print it out.

            

 

 

            Read a character and store it in the character array, and print it after reading 1kb.

            

 

 

    Buffer of character stream:

    

            The emergence of buffers improves the efficiency of operations on streams.

            Principle: In fact, it is to encapsulate the array.

            The corresponding object:

            BufferedWriter:

                      Unique method:

                            newLine(): Cross-platform newline.

            BufferedReader:

                      Unique method:

                            readLine(): Read one line at a time, and return the character data before the line mark as a string when the line mark is reached. When the end is read, null is returned.

 

            When using a buffer object, it should be clear that the buffer exists to enhance the function of the stream.

            Therefore, when creating a buffer object, a stream object must exist first.

            In fact, the buffer is using the method of the stream object, but the data is temporarily stored by adding an array. To improve the efficiency of manipulating data.

 

 

        Reflection on the code:

                Write buffer object.

                //To create a buffer object, you must pass the stream object as a parameter to the buffer's constructor.

                BufferedWriter  bufw = new BufferedWriter(new FileWriter("buf.txt"));

                bufw.write("abce");//Write the data to the buffer.

                bufw.flush();//Flush the data in the buffer. Flush the data to the destination.

                bufw.close();//Close the buffer, in fact, close the stream object that is wrapped inside.

 

 

                Read buffer object.

                BufferedReader  bufr = new BufferedReader(new FileReader("buf.txt"));

                String line = null;

 

                // Get the data in the form of rows. Each row of data fetched does not contain a carriage return.

                while((line=bufr.readLine())!=null)

                {

                    System.out.println(line);

                }

                bufr.close();

 

                Exercise: Copy the text file in the form of a buffer.

                        

                        public static void main(String[] args) {

                                    BufferedReader bufr = new BufferedReader(new FileReader("a.txt"));

                                    BufferedWriter  bufw = new BufferedWriter(new FileWriter("b.txt"));

                                    String line = null;

                                    while((line = bufr.readLine())!= null)  {

                                            bufw.write(line);

                                            bufw.newLine();

                                            bufw.flush();

                                    }

                                    bufw.close();

                                    bufr.close();

                        }

 

                The principle of readLine(): method:

                        In fact, this method in the buffer uses the read method of the stream object associated with the buffer.

                        However, every time a character is read, no specific operation is performed first, and temporary storage is performed first.

                        When the carriage return flag is read, the data stored in the temporary container is returned at one time.

 

                        Now that the principle is clear, we can also implement a method with a similar function.

                        class  MyBufferedReader  {

                                 private  Reader  r;

                                 MyBufferedReader(Reader r) {

                                            this.r = r;

                                    }

                                 public  String myReadLine()  throws  IOException  {

                                            //1: Create a temporary container.

                                            StringBuilder sb = new StringBuilder();

                                            //2: Use the read method to continuously read characters in a loop.

                                             int ch = 0 ;

                                             while((ch = r.read())!=-1) {

                                                        if(ch == '\r')

                                                                continue;

                                                        if(ch == '\n')

                                                                 return sb.toString

                                                        else 

                                                                 sb.append((char)ch);

                                                }

                                                if(sb.length()!=0)

                                                        return sb.toString();

 

                                                return  null;

                                            }

 

                                            public  void  myClose()  throws IOException   {

                                                       r.close();

                                            }

                                }

 

 

 

                                main()   {

                                               MyBufferedReader myBufr = new MyBufferedReader(new  FileReader("a.txt"));

                                               String line = null;

 

                                                while((line = myBufr.myReadLine())!=null)  {

                                                                System.out.println(line);

                                                }

                                }

 

                                It appears based on and enhances the functionality of streams.

                                This is also the embodiment of a design pattern: the decorative design pattern.

                                Enhancements to a set of objects.

 

                                What is the difference between this pattern and inheritance?

                                It has better flexibility than inheritance.

 

                                Usually both the decorating class and the decorated class belong to the same parent class or interface.

 

                                Writer

                                        --->MediaWriter

                                        --->TextWriter

 

                                (Note: The two classes MediaWriter and TextWtiter do not exist in the JDK. They are "created" for a more vivid example, don't misunderstand.)

                                Requirement: If you want to improve the efficiency of data operations, buffering technology is used.

                                        through learned inheritance features. You can create a subclass to override the write method of the parent class. Just

 

 

 

                                Writer: (Note: Do not misunderstand, the following two objects do not exist, just for example.)

                                        --->MediaWriter

                                                    --->BufferedMediaWriter

                                        --->TextWriter

                                                    --->BufferedTextWriter

 

                                When there are too many subclass objects in Writer, in order to improve the efficiency of each object, each object has its own subclass Buffered.

                                Although it can be achieved, the inheritance system becomes very bloated.

 

                                So is it possible to optimize it?

                                In fact, subclasses are using buffering technology.

                                Can you describe the buffering technology, just pass the object that needs to be enhanced to the buffer.

 

                                class BufferedWriter  {

                                         BufferedWriter(MediaWriter mw)   {}

                                         BufferedWriter(TextWriter mw)    {}

                                }

 

 

                                Although this class has completed the enhancement of the existing two objects.

                                But when new objects appear, continue to add constructors to the class. This is not conducive to expansion and maintenance.

                                It is enough to operate on these object parent types. This is polymorphism, which improves the scalability of the program.

 

                                At the same time, BufferedWriter also has a write method, but it is an enhanced write.

                                So BufferedWriter should also be a subclass of Writer.

                                class BufferedWriter extends Writer  {

                                        private Write w;

                                        BufferedWriter(Writer w) {

                                                        this.w = w;

                                        }

                                 }

 

 

                                Writer

                                        --->MediaWriter

                                        --->TextWriter

                                        --->BufferedWriter

                                This will reveal decorative design patterns, optimizing sections for enhanced functionality. Much more flexible than inheritance.

 

 

 

 

A line number can be added on top of reading a line.

class   MyLineNumberReader  extends  MyBufferedReader  {

            private int number;

            MyLineNumberReader(Reader r) {

                super(r);

            }

            public String myReadLine(){

                number++;

                return super.myReadLine();

            }

 

            public void setNumber(int number)  {

                        this.number = number;

            }

 

            public  int  getNumber()  {

                        return  number;

            }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325942988&siteId=291194637