Dark Horse programmer ____ basic enhancement ____ [personal summary of IO stream]

Source: Internet
Author: User

-------------------------------------- Android training, java training, and hope to communicate with you! ------------------------------------

 

The knowledge of the IO stream system is summarized and deepened, and EditPlus is used for coding.

 

For data transmission between IO stream (key) devices, io operations may throw IOException due to the underlying device of the operating system. To process IO operations, you must recognize the concept of "stream, read is used to get data into the stream, and write is the main system for writing data in the stream: abstract base class, all derived subclasses use the parent class as the suffix ---------------------------------- IO inheritance system "*" is more commonly used ;"♂"&"♀"For the Closeable and Flushable interfaces implemented by using the middleware stream inheritance system // Reader, provide close () and flush () feature Reader --> InputStreamReader "*" conversion stream, also known as bridge stream --> FileReader "*" // it can be seen that byte stream is called by the hidden stream at the underlying layer --> BufferedReader "*" buffer & Decoration --> subclass: lineNumberReader row operation --> CharArrayReader Operation character array --> StringReader operation string // Writer implementation interface Closeable, Flushable, Appendable one more append () the Appendable interface appears in Writer 1.5 --> OutputStreamWriter "*" --> FileWriter "*" // The append method is used to add characters --> BufferedWriter "*" --> PipedWriter --> PrintWriter print stream "*" --> CharArrayWriter --> StringWriter byte stream inheritance system: // InputStream implements Closeable interface close () InputStream --> FileInputStream "*" --> FilterInputStream filter stream --> BufferedInputStream byte stream buffer (decoration) --> DataInputStream basic data type --> SequenceInputStream merge stream --> ObjectInputStream"♀"Deserialization of stream objects to read object data into the stream --> PipedInputStream"♂"Pipeline stream, send --> ByteArrayInputStream byte array // OutputStream implements Closeable, Flushable interface close () & flush () outputStream --> FileOutputStream "*" --> FilterOutputStream --> BufferedOutputStream --> PrintStream print stream --> DataOutputStream --> ObjectOutputStream"♂"Object serialization persistence, the object must implement Serializable" Mark interface "--> PipedOutputStream"♀"Pipeline stream, receiving --> ByteArrayOutputStreamIO system other related class File" * "Operation File and directory RandomAccessFile random read/write Properties this class is a subclass of Hashtable, located in java. in the util package, ----------------------------- upload stream FileReader: new FileReader (File)/* Existing File */--> (loop) int read () | int read (char []) --> operation -- (-1) --> close () FileWriter write step: new FileWriter (File)/* Create | overwrite */--> (loop) write (...) --> flush () --> close () File continued write: new FileWriter (File, true )... // change true to false to overwrite the original file. Copy of character files is the cyclic read () and write () bytes stream buffer: Used to improve efficiency "decorative class" BufferedReader read: new BufferedReader (new FileReader (File) --> (loop) string ReadLine () --> operation -- (null loop ends) --> close () subclass: LineNumberReader usage: new LineNumberReader (new FileReader (File ))//. setLineNumber (int n) sets the row number, starting from row n readLine () |. getLineNumber () Get the row number BufferedWriter write: new BufferedWriter (new FileWriter (File) --> (loop) write (linne) --> newLine () --> flush () --> clo Se () using the buffer can reduce the number of reads and writes and improve the efficiency of the design mode-"decorative design mode" Decorator when you want to enhance the functionality of existing objects, you can define classes, introduce existing objects and provide enhanced functions based on existing functions. The custom class called the decoration class readLine () is the enhancement of the read () method, bufferedReader is an enhanced class of the FileReader class. Compared with the inheritance extension, the decoration mode reduces the correlation between the two classes, avoids the bloated inheritance system, and has higher flexibility and scalability. The reading of the byte stream FileInputStream is as follows: new FileInputStream (File) --> (loop) int read () | read (byte []) --> operation -- (-1 loop ends) --> close () method 3: new FileInputStrea M (File) --> new byte [FCM. available ()] --> read (byte []) --> close () // available returns the number of valid bytes of the object in the file. Data is written in one time instead of in a loop, when large files are used with caution (JVM memory allocation is 64 MB by default), array buffering is often dozens of times better than single-byte read/write, you can use the "template mode" to compare the efficiency of the three methods. Generally, the buffer size is about 1 MB, and the validity rate is the highest. Of course, FileOutputStream may be written in different system environments: new FileOutputStream (File) --> write (byte []) --> close () BufferedInputStreamBufferedOutputStream custom byte stream buffer <=> read & write features data in the computer is saved in binary format, it is accessed in bytes. When reading the file, it is easy to convert the binary into decimal. The read method of the byte stream uses the returned value-1 to indicate that it reaches the end of the file. If there are eight consecutive 1 s, if the value is converted to int type-1, the program is terminated early because the control conditions of read method-1 are accidentally met, therefore, the read method of the byte stream buffer must avoid this problem. Solution: Convert byte to int, then fill in 0 byte-1 --> int-1 11111111 11111111 11111111 11111111 & 00000000 00000000 00000000 11111111/255 -------------------------------------------- 00000000 00000000 00000000 11111111 // int through the binary "&" operation. Why? the reason why the returned value of the read method is int instead of byte when reading a single byte -------------- ------------------------- Read the standard input/output stream for keyboard input: System. in (InputStream) & System. out (PrintStream) Conversion stream: The most common form of InputStreamReaderOutputStreamWriter keyboard input: BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); // character <-- byte BufferedWriter bufw = new BufferedWriter (new InputStreamReader (System. out); // character --> byte setting source and purpose: System. setIn (new FileInputStream ("ReadIn. java "); // The source can also directly spread bytes into the conversion stream System. setOut (new P RintStream ("printStream.txt"); // purpose, FileOutputStream can also be 1) the biggest difference between a byte stream and a secondary stream is that a byte stream can operate on any data, while a secondary stream can only operate on text data. 2) The Bytes stream calls the buffer zone of the byte stream at the underlying layer, so the refresh action is required. The byte stream generally does not need to refresh the data stored in binary format on the hard disk, byte (8 bits) is used as the unit. The byte streams read and write operations are measured in bytes. The byte streams call byte streams at the underlying layer, which are used for operating characters, the Unit object operated by the read and write methods is to distinguish between "Source" and "purpose" when using char. Is the operation object plain text? Character: byte ------------------------------------ another important class in the IO stream "File" class is the abstract representation of files and directory path names. This operation is used to add, delete, modify, and Query files. Two interfaces are used to filter File names in the FilenameFilter path. Example: Filter to obtain files in a specified folder. java File dir = new File ("f: \ JAVA \ test"); String [] arr = dir. list (new FilenameFilter () {// anonymous internal class public boolean accept (File dir, String name) {return name. endsWith (". java "); // String class method}); Java cross-platform separator" separator "" recursion ": that is, the function itself uses recursion. Note: 1) there must be clear recursive ending conditions; avoid endless loops; 2) control the number of calls; Avoid stack memory overflow; 3) recursive writing is concise, but inefficient. Avoid using it in algorithm questions: traverse the files and Their subdirectories in a specified directory And perform operations on it --------------- Properties class Properties is a subclass of hashtable, with the characteristics of map set, the stored key-value pairs are strings, this set can be loaded into the IO stream. This class provides some applications that are familiar with io stream operation methods: System running log: Properties prop = System. getProperties (); get data from the configuration file, store the data in the form of key-value pairs, and perform operations. For example, if the software running times are limited to time = 5; when the service is stopped, "Print stream" PrintWriter & PrintStream can be used to directly operate the input stream and files. PrintWriter out = new PrintWriter (new FileWriter ("... "), true) PrintWriter's print & println is a commonly used output statement sop. // This method can be automatically refreshed, and the line feed" merge stream "SequenceInputStream is used to merge Multiple Input streams, to the same output stream "file segmentation", that is, an input stream corresponds to multiple output streams, the output size is in the unit of a buffer array. "file merging" means that multiple input streams direct to the same output stream. The following is an Enumeration example of a Vector & Enumeration: List array set: Vector.
 
  
V = new Vector
  
   
V. add (new FileInputStream (File ))... // Add Multiple Input streams new SequenceInputStream (v. elements (); // this parameter is of the enumeration type and is used to merge the source definition output... in read/write operations, the use of Vector + Enumeration is not efficient. The use of ArrayList + iteration instead of SequenceInputStream must be of Enumeration type. Therefore, it is necessary to re-write the method example in the Enumeration interface: Define the combination of ArrayList and Iterator: new SequenceInputStream (new Enumeration
   
    
() {Public boolean hasMoreElements () {// interface-type anonymous internal class return it. hashNext () ;}// use iteration results as enumeration results to improve efficiency public FileInputStream nextElement () {return it. next () ;}}) "sequence stream" ObjectInputStream & ObjectOutputStream must be used in pairs in two classes: readObject () & writeObject () to continue using object data during the next program execution, out serialization stores the object to the hard disk. in deserialization reads data from the hard disk to serialize (persist) and deserialize the object, the class of the object to be operated must implement Serializable "Mark interface" serialization example: class Person implements Serializable // the object to be operated must implement the mark interface new ObjectOut PutStream (new FileOutputStream ("obj.txt ")). writeObject (person) // write the object to the file new ObjectInputStream (new FileInputStream ("obj.txt ")). readObject () // read objects from a file note: serialization operates on objects in the heap, so static members cannot be serialized by private members, the UID can be used to break this restriction. If the non-static member is modified with the transient, the "pipeline stream" PipedInputStream & PipedOutputStream will not be serialized. The two classes are also used together, and the input and output of the general stream are not closely correlated, the input and output of the pipeline stream can be directly connected, and the communication pipeline must be connected to each other to create a communication pipeline. To be used in combination with multiple threads, a single thread may experience a deadlock. Example: class Read implements Runnable {} // encapsulate the thread task class Write implements Runnable {} main // The main function calls PipedInputStream in = new PipedInputStream (); pipedOutputStream out = new PipedOutputStream (in); // The constructor in can also be a null parameter, and then in. connect (out) is associated with new Thread (new Read (in )). start (); // create a Thread new Thread (new Write (out )). start (); blocking method, use to prevent thread deadlock Object --> RandomAccessFile random read/write powerful random read/write feature: Specify the read/write permission when constructing an Object, "r" read-only, "rw" reads and writes seek (8 * x) method, starting from a certain position of the file through the pointer The read/write class is a member of an I/O package and has the file read/write function. The random byte input stream and output stream are encapsulated internally because a byte [] array is encapsulated internally, you can use the pointer to operate on the elements of the array, getFilePointer to obtain the pointer position, and seek to change the pointer position. Example of creating an object: new RandomAccessFile ("File", "rw") // The RandomAccessFile class can be used for P2P download if multithreading technology is introduced, this greatly improves the efficiency other similar classes distinguish the tag interface in the RandomAccess util package and are implemented by List, which indicates that it supports fast random access. This class is not directly related to RandomAccessFile, see also the Random class in this package. random () of the Math class in the lang Package () the method also provides the random function "Dice" ------------------------------------------ other basic data streams DataInputStream & DataOutputStream to encapsulate byte streams when specially operating the stream object construction of basic data types. Use writeInt (22; the data type read by readInt (). For int, not byteByteArrayInputStream & ByteArrayOutputStream, It is specially used to operate the "Byte" array data source as the byte array CharArrayReader & CharArrayWriter operation "character" array StringReader & StringWriter operation string encoding problem: if the code table during encoding is inconsistent with the code table during decoding, it will lead to garbled characters. The conversion stream has the following constructor example: new InputStreamReader (new FileInputStream ("gbk.txt"), "UTF-8") // specify the UTF-8 decoding process: string -- encoding --> byte [] -- Decoding --> String "intermediate code": the code table on the client and server is inconsistent. For example, a server (iso8859-1) web page in the client (Chinese GBK) Open may generate garbled, so to add the secondary encoding and decoding process, the garbled code according to the iso8859-1 code table into byte, and then the data according to GBK decoding should pay attention to: as the intermediate code, must maintain the data accuracy, that is, a character occupies less than the "Terminal code". For example, if the terminal code is GBK, UTF-8 cannot be used as the intermediate code, because some UTF-8 characters occupy three bytes, gbk is two. Some bytes are added according to the UTF-8 code table during the secondary encoding process, resulting in loss of data precision and garbled characters. "Why can't I use a byte stream to copy images?" byte streams can operate on any file, because the operating unit is the most basic type of data storage. byte streams can only be used for text operations, the basic data type of the operation is char, a character generally occupies 2 (1 ~ 3) byte streams use byte streams at the underlying layer and get characters through the query encoding table (unicode by default in java, if the character corresponding to these two bytes can be found in the code table, the char will be returned, and-1 will be returned if there is no corresponding character. Therefore, if the delimiter stream operates on text, the bytes in the file can be found in the code table, so data will not be lost. If the bytes stream operates on non-text files, it is impossible to ensure that all the bytes can find the corresponding characters in the code table, and the bytes that cannot find the characters disappear with the-1 returned, resulting in loss of bytes and data corruption.
   
  
 


 

 

-------------------------------------- Android training, java training, and hope to communicate with you! ------------------------------------

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.