Java learning ----------- IO stream

1, IO stream overview

  1. brief introduction

A file is usually composed of a series of bytes or characters. The byte sequence constituting the file is called byte stream, and the character sequence constituting the file is called character stream. Java can be divided into input stream and output stream according to the direction of stream. Input stream is the process of loading files or data from other input devices into memory; The output stream, on the contrary, saves the data in memory to a file or other output device.

  1. classification

The file is composed of characters or bytes. Loading the file into memory or outputting the file to the file requires the support of input and output streams. In the Java language, the input and output streams are divided into two, byte input and output streams and character input and output streams.

  1. Four families of IO streams
1. java.io.InputStream;//Byte input stream
2. java.io.OutputStream;//Byte output stream
3. java.io.Reader;//Character input stream
4. java.io.Writer;//Character output stream
  1. Flow to master under java.io package
File Exclusive:
 1. java.io.FileInputStream;
 2. java.io.FileOutputStream;
 3. java.io.FileReader;
 4. java.io.FileWriter;
Conversion flow:
 5. java.io.InputStreamReader;
 6. java.io.OutputStreamWriter;
Buffer stream:
 7. java.io.BufferedReader;
 8. java.io.BufferedWriter;
 9. java.io.BufferedInputStream;
 10. java.io.BufferedOutputStream;
Data flow exclusive:
 11. java.io.DataInputStream;
 12. java.io.DataOutputStream;
Standard input / output stream:
 13.java.io.PrintWriter;
 14.java.io.PrintStream;
Object specific flow:
 15.java.io.ObjectInputStream;
 16.java.io.ObjectOutputStream;
  1. Schematic diagram of inheritance structure of byte stream and character stream

Byte stream:

Character stream:

1. InputStream byte input stream

  1. summary

InputStream is a byte input stream. InputStream is an abstract class. All classes that inherit InputStream are byte input streams. Its subclasses are as follows.

  1. Main methods
1.close();//Close this input stream and free all system resources associated with the stream
2.read();//Reads the next data from the input stream
3.read(byte[] b);//A certain number of bytes are read from the input stream and stored in the buffer array b.
4.read(byte[] b, int off, int len);//Read up to len data bytes in the input stream into the byte array  

2. OutputStream byte output stream

  1. Inheritance subclass
  2. Main methods
1.close();//Close this output stream and free all system resources associated with this stream
2.flush();// Refresh this output stream and force all buffered output bytes to be written out
3.write(byte[] b);//Writes b.length bytes from the specified byte array to this output stream
4.write(byte[] b, int off, int len);//Writes len bytes from the offset off in the specified byte array to this output stream
5.write(int b);//Writes the specified byte to this output stream

3. Reader character input stream

  1. Inheritance subclass

  1. common method
1.close();//Close the flow
2.read();//Read single character
3.read(char[] c);//Read characters into array
4.read(char[] c, int off, int len);//Read characters into a part of an array

4. Writer character output stream

  1. Inheritance subclass


2. Common methods

1.append(char c); //The specified character is appended to this writer
2.close();//Close this stream, but refresh first
3.flush();//Refresh this stream
4.write(char[] c);//Write character array
5.write(char[] cbuf, int off, int len);//Writes a part of a character array
6.write(int c);//Write a single character
7.write(String str);//Write string
8.write(String str, int off, int len);//Writes a part of a string

2, File stream

1. Classification

File byte input stream, file byte output stream, file character input stream, file character output stream

2. FileInputStream file byte input stream

Syntax format:

InputStream is = null;
try {
     is = new FileInputStream("c:\\test.txt");
     int b = 0;
      while ((b = is.read()) != -1) {
         //Direct printing
         //System.out.print(b);
         //Output character
         System.out.print((char)b);
      }
   }catch(FileNotFoundException e) {
      e.printStackTrace();
   }catch(IOException e) {
      e.printStackTrace();
   }finally {
      try {
          if (is != null){
             is.close();
          }
      }catch(IOException e) {
         e.printStackTrace();
      }
} 

3. FileOutputStream file byte output stream

Syntax format:

InputStream is = null;
OutputStream os = null;
try {
    is = new FileInputStream("c:\\test.txt");
    os = new FileOutputStream("d:\\test.txt.bak");
    int b = 0;
    while ((b = is.read()) != -1) {
       os.write(b);
    }
    System.out.println("File copy completed!");
} catch (FileNotFoundException e) {
    e.printStackTrace();

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
      if (is != null){
        is.close();
      }
      if (os != null) {
        os.close();
      }
   } catch (IOException e) {
       e.printStackTrace();
   }
}  

4. FileReader file character input stream

Syntax format:

Reader r = null;
try {
    r = new FileReader("c:\\test.txt");
    int b = 0;
    while ((b = r.read()) != -1) {
     //Output character 
       System.out.print((char)b);
     }
} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
} finally {
     try {
       if (r != null) {
         r.close();
       }
    } catch (IOException e) {}
}

5. FileWriter file character output stream

Syntax format:

try {
    //The following methods will overwrite the contents of the file
    //w = new FileWriter("c:\\test.txt");
    //w = new FileWriter("c:\\test.txt", false);
    //The following is true, which means that it is appended to the file
    w = new FileWriter("c:\\test.txt", true);
    w.write("Hello Hello!!!!");
    //Line feed
    w.write("\n");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
     if (w != null){
       w.close();
     }
   } catch (IOException e) {}

}

3, Buffer stream

1. General

Buffer streams mainly exist to improve efficiency and reduce the number of physical reads. Buffer streams mainly include BufferedInputStream, BufferedOutputStream, BufferedReader and BufferedWriter. BufferedReader provides a practical method readLine(), which can directly read a line, and BufferWriter provides newLine(), which can write line breaks.

2. BufferedOutputStream and BufferedInputStream examples

InputStream is = null;
OutputStream os = null;
try {
    is = new BufferedInputStream(new FileInputStream("c:\\test.txt"));
    os = new BufferedOutputStream(newFileOutputStream("d:\\test.txt.bak"));
    int b = 0;
    while ((b = is.read()) != -1) {
       os.write(b);
     }
    //Manually call flush to write the contents of the buffer to disk
    //It can also be called manually. When the cache is full, it will be clear automatically
    //When the output stream is closed, flush will be called first
    os.flush();
    System.out.println("File copy completed!");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
       if (is != null){
          is.close();
       }
       if (os != null) {
         //flush will be called before close
         os.close();
       }
    } catch (IOException e) {}
}

3. BufferedReader and BufferedWriter examples

BufferedReader r = null;
BufferedWriter w = null;
try {
    r = new BufferedReader(
    new FileReader("c:\\test.txt"));
    w = new BufferedWriter(
    new FileWriter("d:\\test.txt.bak"));
    String s = null;
    while ((s = r.readLine()) != null) {
       w.write(s); 
       //w.write("\n");
      //You can wrap lines as follows
       w.newLine();
    }
    System.out.println("File copy completed!");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
     if (r != null) {
      r.close();
     }
     if (w != null) {
      //flush will be called before close
      w.close();
     }
   }catch(IOException e) {}
}

4, Conversion flow

1. General

There are two main conversion streams: InputStreamReader and OutputStreamWriter. InputStreamReader is mainly used to convert byte stream input stream into character input stream. OutputStreamWriter is mainly used to convert byte stream output stream into character output stream

2. InputStreamReader

BufferedReader br = null;
try {
    br = new BufferedReader(
    new InputStreamReader(
    new FileInputStream("c:\\test.txt")));
    String s = null;
    while ((s = br.readLine()) != null) {
       System.out.println(s);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
       if (br != null) {
          br.close();
       }
    }catch(IOException e) {}
}

3. OutputStreamWriter

BufferedWriter bw = null;
try {
    bw = new BufferedWriter(
    new OutputStreamWriter(
    new FileOutputStream("c:\\603.txt")));
    bw.write("asdfsdfdsf");
    bw.newLine();
    bw.write("Good scenery");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
      if (bw != null) {
         bw.close();
      }
    } catch (IOException e) {}
}

5, Print stream

1. General

The print stream mainly includes two: PrintStream and PrintWriter, which correspond to byte stream and character stream respectively

2. PrintStream redirect output

OutputStream os = null;
try {
   os = new FileOutputStream("c:/console.txt");
   System.setOut(new PrintStream(os));
   System.out.println("asdfkjfd;lldffdfdrerere");
} catch (FileNotFoundException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
} finally {
    try {
       if (os != null) {
         os.close();
        }
     }catch(IOException e) {}
}

3. System.in accepts screen input

BufferedReader br = null;
try {
    br = new BufferedReader(
    new InputStreamReader(System.in));
    String s = null;
    while ((s=br.readLine()) != null) {
       System.out.println(s);
       //Exit loop for q
      if ("q".equals(s)) {
          break;
      }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
       if (br != null) {
       br.close();
    }
   } catch (IOException e) {}
}

6, Object flow

1. General

Object stream can convert Java objects into binary and write them to disk. This process is usually called serialization, and you can also read complete Java objects from disk. This process is called deserialization. Object streams mainly include ObjectInputStream and ObjectOutputStream

2. How to realize serialization and deserialization

  • serialize

If serialization is implemented, the class must implement the serialization interface java.io.Serializable, which has no method. The interface is just a tag interface, and the tag class can be serialized.

ObjectOutputStream oos = null;
try {
    oos = new ObjectOutputStream(
    new FileOutputStream("c:/Person.dat"));
    Person person = new Person();
    person.name = "Zhang San";
    oos.writeObject(person);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}catch(IOException e) {
    e.printStackTrace();
}finally {
    try {
       if (oos != null) {
         oos.close();
       }
    }catch(IOException e) {}
}
class Personn implements Serializable {
      String name;
}
  • Deserialization
ObjectInputStream ois = null;
try {
    ois = new ObjectInputStream(
    new FileInputStream("c:/Person.dat"));
    //Deserialization
    Person person = (Person)ois.readObject();
    System.out.println(person.name);
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}catch(IOException e) {
    e.printStackTrace();
} finally {
    try {
       if (ois != null) {
          ois.close();
       }
    } catch (IOException e) {}
}

class Person implements Serializable {
     String name;
     //Use the transient keyword to modify this property, which will be ignored during serialization
     transient int age;
}

3. Define serialization version number to solve version conflict

//Add the following code to the class
private static final long serialVersionUID = -111111111111111111L;

The above code can be used to solve the following problems. For example, the current Pearson class only has a String name attribute. When serializing Pearson, a version number serialVersionUID will be generated. After adding a sex attribute, the version number will be regenerated when in use. At this time, the JVM considers these two classes incompatible. It can be solved by using a custom serialization version number. Where serialVersionUID is only related to serialization.

7, File class

1. Create a new file and folder in Java

//createNewFile(),delete(),mkdir(),mkdirs()
File file = new File("test.txt");
File dir = new Flie("D:\\course\\Java");
dir.mkdir();
dir.mkdirs();
file.createNewFile();

2. Function for judging files

1.exists();//Determine whether the file exists
2.isFile();//Test whether the File represented by the current File object is a "normal" File
3.isAbsolute();//Test whether the File represented by the current File object is an absolute pathname
4.isDirectory();//Test whether the File represented by the current File object is a path
5.canRead();//Test whether the application can read from the specified file
6.canWrite();//Test whether the application can write the current file
7.isHidden();

3. File attribute function

1.lastModified();//Returns the last modified time of the File represented by the current File object
2.length();//Returns the File length represented by the current File object
3.list();//Returns the File list of the path specified by the current File object
4.listFiles();
5.renameTo();
6.getName();//Returns the file name or pathname representing the current object (if it is a path, the last level of sub pathname is returned)
7.getParent();//f returns the parent directory name of the directory (the last level subdirectory) corresponding to the current File object
8.getPath();//The returned path is the path at the time of definition, which may be a relative path or an absolute path, depending on whether the relative path or the absolute path is used at the time of definition
9.getAbsolutePath();//Returns the absolute pathname of the file represented by the object
10.delete();//Deletes the file specified by the current object

8, Data flow

1. General

DataOutputStream data output stream allows applications to write basic Java data types to the basic output stream, and DataInputStream data input stream allows applications to read basic Java types from the underlying input stream in a machine independent manner

2. DataInputStream

Detailed explanation of internal methods

1.read(byte b[])---Read data from the data input stream and store it in a byte array b in.
2.read(byte b[],int off,in len)---Read data from the data input stream and store it in an array b inside,Position from off start,Count Reg len Bytes.
3.readFully(byte b[])---Loop read from data input stream b.length Bytes to array b in.
4.readFully(byte b[],int off,in len )---Loop read from data input stream len Byte to byte array b in.from b of off Position start
5.skipBytes(int b)---skip n Bytes.
6.readBoolean()---Reads Boolean values from the data input stream.
7.readByte()---Reads a byte from the data input stream.
8.readUnsignedByte()---Reads an unsigned byte from the data input stream,Convert return value to int type.
9.readShort()---Read a from the data input stream short Type data.
10.readUnsignedShort()---Reads an unsigned from the data input stream short Type data.
11.readChar()---Read a character data from the data input stream
12.readInt()---Read a from the data input stream int Type data.
13.readLong()---Read a from the data input stream long Type of data.
14.readFloat()---Read a from the data input stream float Type of data.
15.readDouble()---Read a from the data input stream double Type of data.
16.readUTF()---For reading from the data input stream UTF-8 Format coded UniCode String in character format.

3. DataOutputStream

Detailed explanation of internal methods

1.intCount(int value)---The number of bytes added to the data output stream.
2.write(int b)---take int Type b Write to data output stream.
3.write(byte b[],int off, int len)---Byte array b in off Position start,len A length is written to the data output stream.
4.flush()---Refresh data output stream.
5.writeBoolean()---Writes Boolean data to the data output stream,The bottom layer is converted into a byte and written to the basic output stream.
6.writeByte(int v)---Writes a byte to the data output stream(It is actually the basic output stream).
7.writeShort(int v)---Will one short Type of data is written to the data output stream,Bottom will v Convert 2 bytes and write them to the basic output stream.
8.writeChar(int v)---Will one charl Type of data is written to the data output stream,The bottom layer is v Convert to 2 bytes and write to the basic output stream.
9.writeInt(int v)---Will one int Type of data is written to the data output stream,The bottom layer writes 4 bytes to the basic output stream.
10.writeLong(long v)---Will one long Type of data is written to the data output stream,The bottom layer writes 8 bytes to the basic output stream.
11.writeFloat(flloat v)---Will one float Type of data is written to the data output stream,The bottom layer will float convert to int type,Write to underlying output stream.
12.writeDouble(double v)---Will one double Type of data is written to the data output stream,The bottom layer will double convert to long type,Write to underlying output stream.
13.writeBytes(String s)---Writes the string to the underlying output stream in byte order.
14.writeChars(String s)---Writes strings to the underlying output stream in character order.
15.writeUTF(String str)---Use in a machine independent manner utf-8 Encoding writes the string to the underlying output stream.
16.size()---The number of bytes written to the data output stream.

9, IO + properties access profile

The properties class is a subclass of hashtable. It has the characteristics of map collection, and the key value pairs stored in it are all characters. Properties can be saved in or loaded from a stream. Its load() method can get key value pairs from the configuration file.

 Properties properties = new Properties();
 FileReader fr = null;
 try {
       //fr = new FileReader("C:\\Users\\ASDS\\Desktop\\class1.txt");
     fr = new FileReader("src\\demo1\\class2.txt");
     properties.load(fr); //Get key value pairs from the class.txt file
     fr.close();
} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
}
String username = properties.getProperty("username");//get class.text className value
String password = properties.getProperty("password");//get class.text  methodName value
 
System.out.println(username);
System.out.println(password);

Tags: Java

Posted on Mon, 20 Sep 2021 18:38:57 -0400 by neonorange79