JAVA must master skills (2)-Java IO stream learning input and output stream

Java IO stream learning summary one: input and output stream

Please indicate the source for reprinting: http://blog.csdn.net/zhaoyanjun6/article/details/54292148
This article is from [Zhao Yanjun's blog]

Thanks blogger, thanks for sharing

Java flow class diagram structure:


The concept and role of flow:

  A stream is a set of sequential bytes with a starting point and an ending point. It is a general term or abstraction for data transmission. That is, the transmission of data between the two devices is called a stream. The essence of the stream is data transmission. The stream is abstracted into various categories according to the characteristics of data transmission, which facilitates more intuitive data operations.

IO stream classification:
  according to the different types of data processed: character stream and byte stream is
  divided according to the data flow direction: the input stream and output stream
character stream and
  the origin of the byte stream character stream: Because the data encoding is different, There are stream objects that operate efficiently on characters. The essence is actually to check the specified code table based on the byte stream reading. The difference between byte stream and character stream:

  The unit of reading and writing is different: the byte stream is in units of bytes (8bit), and the character stream is in units of characters. The characters are mapped according to the code table, and multiple bytes may be read at a time.

  The processing objects are different: the byte stream can process all types of data (such as pictures, avi, etc.), while the character stream can only process character type data.

  Byte stream: 8-bit binary is read in or read out at a time.

  Character stream: read in or read out is a 16-bit binary.

  Whether the data on the device is pictures or video, text, they are stored in binary. In the end, binary data is all expressed as an 8-bit data unit, so the smallest data unit in a computer is a byte. It means that the byte stream can handle all data on the device, so the byte stream can also handle character data.

in conclusion:

  As long as the processing of plain text data, priority is given to the use of character streams. Otherwise, byte streams are used.

Input stream and output stream The
  input stream can only be read, and the output stream can only be written. The program needs to use different streams according to the different characteristics of the data to be transmitted.

  InputStream InputStream
    InputStream is the parent class of all input byte streams, it is an abstract class.
    ByteArrayInputStream, StringBufferInputStream, FileInputStream are three basic media streams, they read data from Byte array, StringBuffer, and local files.
    PipedInputStream is to read data from the pipeline shared with other threads, and the knowledge related to Piped will be introduced separately later.
    ObjectInputStream and all FilterInputStream subclasses are decorative streams (the main character of the decorator pattern).
  OutputStream OutputStream
    OutputStream is the parent class of all output byte streams, it is an abstract class.
    ByteArrayOutputStream and FileOutputStream are two basic media streams, which write data to the Byte array and local file respectively.
    PipedOutputStream is to write data to the pipe shared with other threads.
    ObjectOutputStream and all FilterOutputStream subclasses are decorative streams.
to sum up:

  Input stream: InputStream or Reader: read from the file to the program;
  output stream: OutputStream or Writer: output from the program to the file;
node stream
  node stream: directly connected to the data source, read in or read out.
  Using the node stream directly is inconvenient to read and write. In order to read and write files faster, there is a processing stream.


Commonly used node streams
  Parent classes: InputStream, OutputStream, Reader, Writer
  files: FileInputStream, FileOutputStrean, FileReader, FileWriter File node processing
  array: ByteArrayInputStream, ByteArrayOutputStream, CharArrayReader, CharArrayWriter node processing array It is a file, but an array in memory)
  String: StringReader, StringWriter Node stream that processes strings
  : PipedInputStream, PipedOutputStream, PipedReader, PipedWriter Node stream
processing stream
  processing stream and node stream are used together On the basis of the node flow, another layer is nested, and the processing flow is nested on the node flow. Such as BufferedReader. The construction method of processing the stream always takes another stream object as a parameter. A stream object is packaged multiple times by other streams, called a stream link.


Commonly used processing stream
  Buffered stream: BufferedInputStrean, BufferedOutputStream, BufferedReader, BufferedWriter increase the buffer function to avoid frequent read and write hard disk.
  Conversion stream: InputStreamReader and OutputStreamReader realize the conversion between byte stream and character stream.
  Data stream: DataInputStream, DataOutputStream, etc.-Provides the basic data types to be written to the file, or read out.
Conversion stream
  InputStreamReader, OutputStreamWriter requires InputStream or OutputStream as parameters to achieve the conversion from byte stream to character stream.

Constructor

InputStreamReader (InputStream); // Initialized by the constructor, using the system's default encoding table GBK. 
  InputStreamReader (InputStream, String charSet); // Through this constructor initialization, you can specify the encoding table. 
  OutputStreamWriter (OutputStream); // Initialized by this constructor, using the system's default encoding table GBK. 
  OutputStreamwriter (OutputStream, String charSet); // Through this constructor initialization, you can specify the encoding table.


  The use of the FileInputStream class in actual combat exercises : reading file content

package com.app;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class A1 {
    public static void main(String[] args) {
        A1 a1 = new A1();

        // computer disk d abc.txt document 
        String filePath = "D: /abc.txt" ;
        String reslut = a1.readFile( filePath ) ;
        System.out.println( reslut ); 
    }

    /**
    * Read the content of the specified file
    * @param filePath: the path of the file
    * The result returned by @ return
     * / 
    public String readFile (String filePath) {
        FileInputStream fis=null;
        String result = "" ;
      try {
          // Instantiate an input stream object 
          fis = new FileInputStream (filePath);

          // 2. Return the estimated value of the remaining bytes that can be read in this input stream; 
          int size = fis.available ();
          // 3. Create a byte array based on the number of bytes in the input stream; 
          byte [ ] array = new  byte [size];
          // 4. Read the data into the array; 
          fis.read (array);

          // 5. Create a new string based on the obtained Byte array, and then output; 
          result = new String (array);

      } catch (FileNotFoundException e) {
          e.printStackTrace ();
      }catch (IOException e) {
          e.printStackTrace ();
      }finally{
          if ( fis != null) {
              try {
                  fis.close();
              } catch (IOException e) {
                  e.printStackTrace ();
              }
          }
      }
  
      return result ;
    }
  }    
}

Use of FileOutputStream class:

  Write content to file

package com.app;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class A2 {

public static void main(String[] args) {
  A2 a2 = new A2();

  // computer disk d abc.txt document 
  String filePath = "D: /abc.txt" ;

  // Content to be written 
  String content = "Today is 2017/1/9, the weather is good" ;
  a2.writeFile( filePath , content ) ;
}
/** * Create an output stream based on the file path * @param filePath: the path of the file * @param content: content to be written * / public void writeFile (String filePath, String content) {   FileOutputStream fos = null ;   try {     // 1. Create an output stream     fos = new FileOutputStream (filePath) according to the file path ;     // 2. Convert the string to a byte array;     byte [] array = content.getBytes ();     // 3 , Output byte array;     fos.write (array);   } catch (FileNotFoundException e) {     e.printStackTrace ();   }catch (IOException e) {     e.printStackTrace ();   }finally{     if ( fos != null) {       try {         fos.close();       } catch (IOException e) {         e.printStackTrace ();       }     }   }  }
}

note:

  In the actual project, all IO operations should be placed in sub-threads to avoid blocking the main thread.
  When FileInputStream reads the content of the file, we pass in the path of the file ("D: /abc.txt"). If the file in this path does not exist, then FileNotFoundException will be reported when the readFile () method is executed.
  When FileOutputStream writes a file, we pass in the path of the file ("D: /abc.txt"). If the file in this path does not exist, then when the writeFile () method is executed, a new one will be created for us document. It is also important to not report an exception.
Effect picture:

  Comprehensive exercises to copy files from D drive to E drive

package com.app;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class A3 {

public static void main(String[] args) {
  A3 a2 = new A3 ();

  // The path of the cat.png picture in the computer d drive 
  String filePath1 = "D: /cat.png" ;

  // The path of the cat.png picture in the computer's e drive 
  String filePath2 = "E: /cat.png" ;

  // Copy file 
  a2.copyFile (filePath1, filePath2);

}

/**
* File copy 
* @param filePath_old: the path of the file to be copied
* @param filePath_new: the path where the copied file is stored
 * / 
public  void copyFile (String filePath_old, String filePath_new) {
  FileInputStream fis=null ;
  FileOutputStream fout = null ;
  try {
    // Instantiate an input stream object 
    fis = new FileInputStream (filePath_old) according to the path path ;

    // 2. Return the estimated value of the remaining bytes that can be read in this input stream; 
    int size = fis.available ();
    // 3. Create a byte array based on the number of bytes in the input stream; 
    byte [ ] array = new  byte [size];
    // 4. Read the data into the array; 
    fis.read (array);

    // 5. Create an output stream based on the file path 
    fout = new FileOutputStream (filePath_new);

    // 5. Output byte array; 
    fout.write (array);

  } catch (FileNotFoundException e) {
    e.printStackTrace ();
  }catch (IOException e) {
    e.printStackTrace ();
  }finally{
    if ( fis != null) {
      try {
        fis.close();
    } catch (IOException e) {
        e.printStackTrace ();
    }
  }
  if ( fout != null ) {
    try {
      fout.close();
    } catch (IOException e) {
       e.printStackTrace ();
    }    
  }
 }
}
}

 

Guess you like

Origin www.cnblogs.com/blmlove/p/12740895.html