Java Basics Summary--io Summary 1

Source: Internet
Author: User
Tags array length readline

1.IO Stream (data Flow) main application Overview
Data source: Stored inside the device
* IO stream is used to process transmission between data between devices
* Java operations on data are streamed through the way
* Java for the operation of the convection objects are in the IO package
* Flow is divided into: output stream (write action) and input stream (read action) (as opposed to program)
Different ways of reading and writing, resulting in different objects being encapsulated
* Number of bytes per operation data: Byte stream (1B) and character stream (2B)
Previously no character stream: ASCII code 1b--expression of English text numbers, random computer popularization, in order to express the language of more countries, compatible with many national code tables, this is not conducive to information communication, unified the Unicode encoding used to represent the language of many languages and symbols, The feature is that any character is represented by 2B-a waste of resources (which can be coded to optimize these issues later). A Chinese character in different code table code is not the same, so I want to read the text message in Unicode encoding, for the same information, to obtain the same result
So use a character stream to manipulate the text.
* Character stream Origin: byte stream after reading bytes data, not directly operation but first check the specified encoding table to obtain the corresponding word, in the operation of the text = = byte stream + encoding table

2. Specific IO objects
Generic extraction--get the root class of Io Stream (abstract class)
BYTE stream: InputStream outputstream
Character Stream: Reader Writer
Whose subclasses end with their corresponding suffixes, the prefix of the object name is the function

3. Transfer text message memory--the file of the hard disk (the output stream that takes precedence to the character stream writer)
Find writer that can manipulate files
Writer-->outputstreamwriter-->filewriter
* Must explicitly store the data destination-file name
* file does not exist automatically created, file exists and has data, file will be overwritten (delete + Create new file)
* Input or output exception--ioexception best to be handled
Specific steps:
1.FileWriter FW = new FileWriter ("Demo.txt");
2. Calling writer's Write method void write ()-the argument can be a string, an array of characters, an int
Fw.write ("ABCD");--this time the data is temporarily stored in the buffer
3. Refresh--store the buffer stream in the destination file
Fw.flush ();
4. Close Windows resources
Fw.close ()--generally written in try-catch-finally (will be executed)
Close () is the--java program, notepad program, etc. writing to the hard disk file is actually called the windows underlying output stream, so after the completion of the write operation, you must release the resources occupied by this stream
Note: Close () {flush ()} is refreshed when the resource is closed
You cannot write data after a stream is closed, but you can continue writing after a refresh
To implement line breaks, direct the operating system's line break command operation
Append Data filewriter (String filename, boolean append)-Append True
Close differs from flush: the latter is equivalent to opening a file write save, the latter to close the file, ask whether to save, close the file. Opening the file again is the new stream.

4. Exception handling IOException (exceptions may occur if read and write)
File does not exist, write fails, close underlying resource will also throw an exception
-catch-finally (Close ()) using the try (the statement in which the exception is placed)
Note: Declare the object's initialization outside of the try
When closing a resource, determine whether it is a null pointer, and the closing action

5. Read data from a file, print it in console FileReader
read-read a single character, character array, etc.
* Create an object of the file, determine the file name and existence to read
FileReader fr = new FileReader ( String filename)-An exception occurred when the file was not found
* reads a single character
Fr.read ()-int (the range of one character of the 0-655235 char) using the Read () method inside reader; reads to the end returns-1 means end The
Read () method is actually associated with the underlying operating system, reads to the end, passes the end token to the JVM, and then the JVM customizes a match to the caller.
* Usually the action is placed inside the loop
* Second reading method (higher efficiency)
Int read (char[] cbuf)--Returns the number of characters read. The end is-1, the character that will be read into the character array. Note: A space is also considered a character. The length of the character array is fixed
int num = fr.read (ch);//data is read into the character array inside
System.out.println (num + "" + New String (CH)); 3 ABC
int NUM1 = f R.read (CH);//data read into character array 2 Dec
System.out.println (num1 + "" + New String (CH)),//overwrite top two elements
summary above: Write Loop
The data from the hard disk must be a fetch, the character array is to take one in, and so on to the number of
and then unified processing.
Integer multiple of character array length 1024
Eg: copy a file into another file--the copy principle reads and writes-character stream
1. Create a character stream object that reads a file
2. Create a purpose to store read Data
3. Frequent read and write operations
4. Close a resource
Note: read one at a time, accumulate multiple and then write
Write (char[] cbuf, int off, int len)--Multiple options for writing methods at read time

6. Buffer of character stream--use an array to buffer the data in the stream
Why: Improve the efficiency of data read and write--java encapsulate it as two objects
Corresponding class: BufferedReader (character, character array line)/bufferedwriter (character, character array)

Buffer use: To be used in conjunction with the corresponding stream, the enhancement of the convection function on the basis of the flow
Buffer: Temporary storage of the data to be manipulated, less head switching, high efficiency
Code Optimization: Design Optimization (code refactoring), performance optimization (increased function-buffer) eg: Supermarket grab box
Buffers must be manipulated in conjunction with a stream to function--increase efficiency
Specific write Data flow--using buffered streams
Create a stream as written
FileWriter FW = new FileWriter ("Demo3.txt");
Creates a stream object written as a character buffer and a character write-out stream to associate
BufferedWriter bw = new BufferedWriter (FW);
Write using buffered streams-continuous write operation
Bw.write ("GGSGHJDJCJMDKKDKD");
Refresh data to destination file
Bw.flush ();
Close resources-in fact, the bottom is the FW, buffering is only to improve efficiency
Bw.close ();
[Character write stream constant write data not processed, put in write buffer stream at specific time unified operation]
NewLine Line_separator defines the constant, which is passed to System.getproperties ();-Precedence selection
You can also use the method to wrap bw.newline ();
The character buffer read Stream--readline ()-string represents a read line (the line is judged by a carriage return)
Can take advantage of a loop return value of NULL when the control loop
[Read stream continuously read the data is not processed, placed in the buffer stream at a specific time unified operation]
BufferedReader overrides the method of the parent class, reads the parent class from the source read the data, the buffer method reads the data from the buffer--simply does not need to read the memory directly, but the direct operation buffer, in order to let the user read the text more convenient-reads the line--will judge the Read method's character, the more to the line , the stop does not contain line breaks

6. Implementation of the analog ReadLine () function
* Implement read () first-read in buffer
Create an array, call FileReader's Read (CHAR[]CH), and define two variables representing the remaining characters in the array, count, and the pose of the set of corners.
* When buffer is 0, start toward buffer party data count = r.read (buff);p ose = 0
* Count < 0 return Direct-1
* Other conditions directly take the character int ch = buff[pose++],count--;
Implementing the ReadLine () method
* Create a new buffer StringBuilder
* Loop join Element call Myread ()
* In the loop, separate judgment \ R uses continue; and \ n returns a string.
* Other conditions read to tail return null
* Note that the ENTER key corresponds to the \r+\n read \ n after a newline

7. Decorative design pattern--enhancement of a function
Buffer main function: will read the source data to store, provide the method of the buffer operation, read memory to read buffer. The presence of a buffer increases the function of the character Stream's operation--decorated mode
Decorator mode: To enhance the existing things, the main body or the original thing
The difference between a decorator and an inheritance:
* Same point: Both decoration and inheritance can extend the function.
* For inheritance: First there is an inheritance system, the following are a variety of sub-class objects, in order to better operate and improve efficiency must be in the generation of new sub-class to provide the extension of the function, which will lead to the system of inheritance bloated, inflexible, once the relationship is generated, the relationship is difficult to remove.
* Decorative pattern: The generation of new classes to the old class function extension, in conjunction with the existing subclass of a feature extension implementation, so that the relationship between classes is not particularly close. More flexible
* Requirements for using decorator mode
Decorator and the decorator have the same parent class or the same parent interface (enhanced with the same method functionality)
eg:bufferedreader& Filereader--reader

8.LineNumberReader (BufferedReader subclass is also decorator)--Get Set current line number
Setlinenumber (int linenumber)
Getlinenumber ()
Enhanced version of BufferedReader

9. Byte stream-manipulating bytes, characters, and other media files
The idea of operation is exactly the same as the character stream
* The buffer used for the inputstram/outputstream--byte stream is an array of bytes byte[]b
Do not write buffer to go directly to the destination, without refreshing, directly shut down resources. It's written in the original code.
Avaliable ()-int the number of bytes that can be manipulated;
* Application of Byte stream--copy mp3
1. Custom buffer Fileinputstram 2. Use encapsulated Bufferedinputstram (write to refresh)
Note: You can not use the character stream to read the picture, because the character stream will be the byte to get after the code table to find out, but for the text has a fixed code table corresponding to the picture without fixed code table, so there may be no information to find the situation, so the copy picture can not represent the original picture

Java Basics Summary--io Summary 1

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.