IO stream

The classification of the flow

According to the direction

  • Input stream: Reads from < storage device > to < memory >
  • Output stream: writes the contents of < memory > to < Storage device >

White piao data

According to the unit

  • Byte stream: In bytes, all data can be read and written
  • Character stream: In characters, only text data can be read and written

According to the function

  • Node flow: Has the read and write function of the actual data transmission
  • Filter flows: Enhances functionality on top of node flows

Byte stream

//InputStream byte InputStream
public int read(a){}
public int read(byte[] b){}
public int read(byte[] b, int off, int len){}

// OutputStream byte OutputStream
public void write(int n){}
public void write(byte[] b){}
public void write(byte[] b, int off, int len){}
Copy the code

White piao data

File byte stream

// 1 Create a FileInputStream and specify the file path
  FileInputStream fis = new FileInputStream("d:\\abc.txt");
  // 2 Read the file
  // fis.read();
/ / 3 closedfis.close(); = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =// 1 Create a file byte output stream
  FileOutputStream fos = new FileOutputStream("Path".true);// True indicates no overwrite
	// 2 Write to the file
  fos.write(97);
  fos.write('a');
/ / 3 closed
  fos.close();
Copy the code

Byte buffer stream

BufferedInputStream/ BufferedOutputStream

  • Improves I/O efficiency and reduces the number of disk accesses
  • Data is stored in a buffer. Flush is to write the contents of the buffer to the file, or close directly
// 1 Create a BufferedInputStream
  FileInputStream fis = new FileInputStream("Path");
  BufferedInputStream bis = new BufferedInputStream(fis);
/ / 3 closed
  bis.close();
Copy the code

White piao data

Object flow

ObjectOutputStream / ObjectInputStream

  • Enhanced buffer functionality
  • Enhanced the ability to read and write 8 basic data types and strings
  • Enhanced the ability to read and write objects

ReadObject () reads an Object from the stream. WriteObject (Object obj) writes an Object to the stream

The process of transferring objects using streams is called serialization, deserialization

serialization

// Use objectoutputStream for serialization
psvm(String[] args){
  // 1. Create an object stream
  FileOutputStream fos = new 		 FileOutputStream("d:\\st.bin");
  ObjectOutputSream oos = new objectOutputSream(fos);
  // 2. Serialization (write operation)
  Student zhangsan = new Student("zs".20);
  oos.WriteObject(zhangsan);
  / / 3. Shut down
  oos.close();
  sout("Serialization finished.");
}
Copy the code

deserialization

// Use ObjectInputSteam to deserialize (read refactored objects)
psvm(String[] args){
  // 1. Create an object stream
  FileInputStream fis = new FileInputStream("d:\\stu.bin");
  ObjectInputStream ois = new ObjectInputStream(fis);
  // 2. Read the file (deserialization)
  Student s = (Student)ois.readObject();
  / / 3. Shut down
  ois.close();
  sout("Execution completed.");
  sout(s.toString());  
}
Copy the code

Serialization Considerations

White piao data

  • A class must implement the Serializable interface to be serialized
  • An object property in a serialization class requires that the Serializable interface be implemented
  • The serialized version ID, which ensures that the serialized and deserialized classes are the same class
  • Using the TRANSIENT modifier, the property cannot be serialized
  • Static properties cannot be serialized
  • Serialize multiple objects, which can be done with collections

Characters of the flow

// Conventional byte stream reads
psvm(String[] args){
  // 1. Create a FileInputStream object
  FileInputSteam fis = new FileInputStream("Path");
  / / 2. Read
  int data = 0;
  while((data = fis.read()) ! = -1){
    sout((char)data); 
  }
  / / 3. Shut down
  fis.close();
}
Copy the code

Character buffer stream

White piao data

BufferedReader / BufferedWriter
Copy the code

Efficient read and write, support input newline character, can write one line at a time read one line

psvm(String[] args) throws Exception{
  // Create a buffer stream
  FileReader fr = new FileReader("..");
	BufferedReader br = new BufferedReader(fr);
  / / read
  // 1
  char[] buf = new char[1024];
  int count = 0;
  while((count = br.read(buf)) ! = -1){
    sout(new String(buf, 0, count));
  }
  // 2. In the second mode, read line by line
  String line = null;
  while((line = br.readLine()) ! =null){
    sout(line);
  }
  
	/ / close
  br.close();
}
psvm(String[] args){
  // 1. Create a BufferedWriter object
  FileWriter fw = new FileWriter("..");
  BufferedWriter bw = new BufferedWriter(fw);
  / / 2. Write
  for(int i = 0; i < 10; i ++){
    bw.write("What is written");
    vw.newLine(); // Write a newline
    bw.flush();
  }
  / / 3. Shut down
  bw.close(); // In this case, the FW is automatically disabled
}
Copy the code

Transformation flows

Bridge conversion stream InputStreamReader/OutputStreamWriter

Converts a byte stream to a character stream

You can set the character encoding mode

psvm(String[] args) throws Exception{
  // 1 Create an InputStreamReader object
  FileInputStream fis = new FisInputStream("..");
  InputStreamReader isr = new InputStreamReader(fis, "utf-8");
  // 2 Read the file
  int data = 0;
  while((data = isr.read()) ! = -1){
    sout((char)data);
  }
  / / 3 closed
  isr.close();
}
Copy the code
psvm(String[] args) throws Exception{
  // 1 Create an OutputStreamReader object
  FileOutputStream fos = new FisOutputStream("..");
  OutputStreamWRITER osw = new OutputStreamReader(fos, "utf-8");
  / / 2 write
  for(int i = 0; i < 10; i ++){
    osw.write("Write content");
    osw.flush();
  }
  / / 3 closed
  osw.close();
}
Copy the code

The File type

/* Use of the File class 1. Separator 2. File operation 3
public class Demo{
  psvm(String[] args){
    separator();
  }
  // 1. Separator
  public static void separator(a){
    sout("Path separator" + File.pathSeparator);
    sout("Name separator" + File.separator);
  }
  // 2. File operation
  public static void fileOpen(a){
    // 1. Create a file
    if(! file.exists()){// Whether it exists
    	File file = new File("...");
    	boolean b = file.creatNewFile();
    }
    
    // 2. Delete the file
    // 2.1 Delete directly
    file.delete(); / / true success
    // 2.2 Delete when using JVM exit
    file.deleteOnExit();
    
    // 3. Obtain file information
    sout("Get the absolute path" + file.getAbsolutePaht());
    sout("Obtain path" + file.getPath());
    sout("Get file name" + file.getName());
    sout("Get the husband directory" + file.getParent());
    sout("Get file length" + file.length());
    sout("File creation time" + new Date(file.lashModified()).toLocalString());
    
    / / 4. The judgment
    sout("Is it writable?" + file.canWrite());
    sout("Is it a document?" + file.isFile());
    sout("Hidden or not" + file.isHidden());
  }
  
  
  // Folder operation
  public static void directoryOpe(a) throws Exception{
    // 1. Create folders
    File dir = new File("...");
    sout(dir.toString());
    if(! dir.exists()){//dir.mkdir(); // Only a single-level directory can be created
      dir.mkdirs(); // Create multi-level directories
    }
    
    // 2. Delete folders
    // 2.1 Delete directly
    dir.delete(); // Only the lowest empty directory can be deleted
    // 2.2 Using JVM to delete
    dir.deleteOnExit();
    
    // 3. Obtain the folder information
 		sout("Get the absolute path" + dir.getAbsolutePaht());
    sout("Obtain path" + dir.getPath());
    sout("Get file name" + dir.getName());
    sout("Get the husband directory" + dir.getParent());
    sout("Get file length" + dir.length());
    sout("Folder creation Time" + new Date(dir.lashModified()).toLocalString());
    
    / / 4. The judgment
    sout("Is it a folder?" + dir.isFile());
    sout("Hidden or not" + dir.isHidden());
    
    // 5. Traverse the folders
    File dir2 = new File("...");
    String[] files = dir2.list();
    for(String string : files){
      sout(string);
    }
    
    // Use of the FileFilter interface
    
    File[] files2 = dir2.listFiles(new FileFilter(){
      
      @Override
      public boolean accept(File pathname){
        if(pathname.getName().endsWith(".jpg")) {return true;
        }
        return false; }});for(File file : files2){ sout(file.getName()); }}}Copy the code

Finally, I wish you all an early success in your studies, a satisfactory offer, rapid promotion and salary increase, and the peak of your life. If you can, please give me a triple support yo, we will see you next time

White piao data