Java IO File Action Notes+Jobs

This note is organized according to the content of the teacher's class and is not 100% original by me

Overview of IO

What is IO?

i: input

o: output

 

Why do I have IO?

You learned File and you can manipulate it

Use IO to manipulate the contents of a file

How to implement IO function in java

Implement IO functionality through stream models

Classification of IO

Divide by flow (using memory as reference)

  • Input stream: external device-->memory read

  • Output stream: Memory--->External device write

By data type

  • Byte stream: Logical unit is byte, 1B = 0000 0000

  • Character Flow: The logical unit is a character (think of it as a cultural symbol, abc, hi, etc.). Essentially transferred or bytes

Four abstract base classes

Byte Output Stream

Byte input stream: InputStream

Character output stream: Writer

Character input stream: Reader

Subclasses derived from these four abstract base classes are suffixed by their parent name

Give an example:

FileOutputStream

FileInputStream

FileWriter

FileReader

What stream is used when?

Character streaming is recommended for text files. Txt. Java. CPP

For non-text files, use byte streams. Mp3. Mp4. Jpg. Png. Avi. Pdf. Word. Ppt. Exe

Byte streams are omnipotent

Byte Stream

Byte Output Stream

Abstract Base Class OutputStream

This abstract class is a superclass of all classes representing the output byte stream

Inheritance relationship

Member Method

 

voidclose() closes the output stream and releases all system resources associated with the stream.
voidflush() flushes this output stream and forces all buffered output bytes to be written out.
voidwrite(byte[] b) writes b.length bytes from the specified byte array to this output stream.
voidwrite(byte[] b, int off, int len) writes len bytes from offset off in the specified byte array to this output stream.
abstract voidwrite(int b) writes the specified bytes to this output stream. The General Convention for write is to write a byte to the output stream. The bytes to be written are the eight low bits of parameter B. The 24 high bits of B will be ignored.

Specific subclasses

FileOutputStream File Byte Output Stream

File output stream is used to write data to File

Inheritance relationship

 

Construction method

FileOutputStream(File file) creates a file output stream that writes data to the file represented by the specified File object.
FileOutputStream(File file, boolean append) creates a file output stream that writes data to the file represented by the specified File object.
FileOutputStream(String fileName) creates an output file stream that writes data to a file with a specified name.
FileOutputStream(String name, boolean append) creates an output file stream that writes data to a file with a specified name.

Member Method

voidclose() closes the output stream and releases all system resources associated with the stream.
voidflush() flushes this output stream and forces all buffered output bytes to be written out.
voidwrite(byte[] b) writes b.length bytes from the specified byte array to this output stream.
voidwrite(byte[] b, int off, int len) writes len bytes from offset off in the specified byte array to this output stream.
voidwrite(int b) writes the specified bytes to this output stream. The General Convention for write is to write a byte to the output stream. The bytes to be written are the eight low bits of parameter B. The 24 high bits of B will be ignored.
package _17io01.com.cskaoyan.bytestream._01fileoutputstream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/23 15:55
 **/

/*
Steps for writing data
1.Create Output Stream Object
2.write
3.close Release Resources
 */
public class Demo {
    public static void main(String[] args) throws IOException {
        //1. Create an output stream object
        //File file = new File("a.txt");
        //FileOutputStream out = new FileOutputStream(new File("a.txt"));
        FileOutputStream out = new FileOutputStream("b.txt");
        //2.write
        // write(int b) write a single byte
        //out.write(97);

        // write(byte[])
        String s = "abc";
        byte[] bytes = s.getBytes();
        //out.write(bytes);
        // Is it abc? Or aabc?

        // write(byte[], int off, int len)
        out.write(bytes, 1, 2);
        //3.close releases resources
        out.close();
    }
}

Matters needing attention

  • What happened when the output stream object was created?

    • Before creating, the jvm will go to the operating system to see if this file exists

    • If it doesn't exist, create it for us

    • If it exists, overwrite the content, rewrite it

  • How to achieve file appending function?

    • Constructing method with append

    • package _17io.com.cskaoyan.bytestream._01fileoutputstream;
      
      import java.io.FileOutputStream;
      import java.io.IOException;
      
      /**
       * @description: files were added
       * @author: Sedum Sedum
       * @date: 2022/6/23 16:42
       **/
      
      public class Demo2 {
          public static void main(String[] args) throws IOException {
              // Create Output Stream Object
              FileOutputStream out = new FileOutputStream("b.txt", true);
              // write
              out.write("Ha ha ha ha".getBytes());
      
              // close
              out.close();
          }
      }
      
  • How to achieve line-breaking function?

    • By line breaks

    • package _17io.com.cskaoyan.bytestream._01fileoutputstream;
      
      import java.io.FileOutputStream;
      import java.io.IOException;
      
      /**
       * @description: Line Break Function
       * @author: Sedum Sedum
       * @date: 2022/6/23 16:42
       **/
      
      public class Demo3 {
          public static void main(String[] args) throws IOException {
              // Create Output Stream Object
              FileOutputStream out = new FileOutputStream("a.txt");
              // write
              out.write("abc".getBytes());
      
              // Write Line Break
              // "\r\n"
              out.write("\r\n".getBytes());
      
              out.write("abc".getBytes());
      
              // "\r"
              out.write("\r".getBytes());
      
              out.write("abc".getBytes());
      
              // "\n"
              out.write("\n".getBytes());
      
              out.write("abc".getBytes());
              //System.lineSeparator() System Default Line Break
              out.write(System.lineSeparator().getBytes());
              out.write("abc".getBytes());
      
      
              // close
              out.close();
          }
      }
      
  • exception handling

    • Traditional try-catch

      • package _17io.com.cskaoyan.bytestream._01fileoutputstream;
        
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        
        /**
         * @description: try-catch
         * @author: Sedum Sedum
         * @date: 2022/6/23 17:13
         **/
        
        public class Demo4 {
            public static void main(String[] args) {
                // Create Output Stream Object
                FileOutputStream out = null;
                try {
                    // Assume there is an exception
                    out = new FileOutputStream("a.txt");
                    // write
                    out.write("abc".getBytes());
                    
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        // close
                        // Make a judgement
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        
    • try-with-resources

      • grammar
        try(Resources,Implemented AutoCloseable Classes of interfaces can be considered resources){
            // Code with possible exceptions
            // The try resource is automatically released
        }catch(){
            
        }
      • package _17io.com.cskaoyan.bytestream._01fileoutputstream;
        
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        
        /**
         * @description: try-with-resources
         * @author: Sedum Sedum
         * @date: 2022/6/23 17:13
         **/
        
        public class Demo5 {
            public static void main(String[] args) {
                // Create Output Stream Object
        
                try(FileOutputStream out = new FileOutputStream("a.txt")) {
        
                    // write
                    out.write("abc".getBytes());
        
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
      • Verify automatic release

      • package _17io.com.cskaoyan.bytestream._01fileoutputstream;
        
        /**
         * @description:
         * @author: Sedum Sedum
         * @date: 2022/6/23 17:22
         **/
        
        /*
        Verify Auto Release Operation
         */
        public class Demo6 {
            public static void main(String[] args) {
                // try-with-resources
                try(A  a = new A()) {
                    // Call func
                    a.func();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //Define a class to implement the AutoCloseable interface
        
        class A implements AutoCloseable{
        
            @Override
            public void close() throws Exception {
                System.out.println("close Executed");
            }
        
            public void func() {
                System.out.println("func Executed");
            }
        }
  • Why close?

    • The io resource is an operating system resource, not a jvm resource, and will not be recycled. It can only be explicitly released by the close method. Only resources that are not part of the jvm are used and generally need to be released.

BufferedOutputStream Buffered Byte Output Stream

This class implements buffered output streams. By setting this output stream, the application can write individual bytes to the underlying output stream without invoking the underlying system for each byte write

Inheritance relationship

 

Construction method

BufferedOutputStream(OutputStream out) creates a new buffered output stream to write data to the specified underlying output stream.
BufferedOutputStream(OutputStream out, int size) creates a new buffer output stream to write data with the specified buffer size to the specified underlying output stream.

 

Member Method

3 Writes

Demo

package _17io.com.cskaoyan.bytestream._05bufferedoutputstream;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description: write data
 * @author: Sedum Sedum
 * @date: 2022/6/24 11:00
 **/

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Create Buffered Output Stream Object
        BufferedOutputStream out =
                new BufferedOutputStream(new FileOutputStream("a.txt"));
        // write
        // Single byte
        out.write(97);
        // Multibyte
        out.write("Treasure,I'm tired today,But I still miss you.".getBytes());
        // flush
        //out.flush();

        // close
        out.close();
    }
}

Be careful:

  • Use buffered streams, remember the flush operation

  • The close method executes flush

  • Auto refresh if buffer is full

 

Byte Input Stream

Abstract Base Class InputStream

This abstract class is a superclass of all classes representing byte input streams.

Inheritance relationship

 

Member Method

abstract intread() Reads the next byte of data from the input stream. Returns an int byte value in the range 0 to 255. If no bytes are available because the end of the stream has been reached, the return value of -1 returns the byte value readData
intread(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B. The total number of bytes read into the buffer; Returns -1 if no data is available because the end of the stream has been reached. Returns the number of bytes read Count
intread(byte[] b, int off, int len) reads the maximum len data bytes in the input stream into the byte array.

Specific subclasses

FileInputStream File Byte Input Stream

FileInputStream gets input bytes from a file in the file system

Inheritance relationship

 

Construction method

FileInputStream(File file) creates a FileInputStream by opening a connection to the actual file specified by the File object file in the file system.
FileInputStream(String fileName) creates a FileInputStream by opening a connection to the actual file specified by the path name in the file system.

Member Method

abstract intread() Reads the next byte of data from the input stream. Returns an int byte value in the range 0 to 255. If no bytes are available because the end of the stream has been reached, the return value of -1 returns the byte value readData
intread(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B. The total number of bytes read into the buffer; Returns -1 if no data is available because the end of the stream has been reached. Returns the number of bytes read Count
intread(byte[] b, int off, int len) reads the maximum len data bytes in the input stream into the byte array.

Demo

package _17io01.com.cskaoyan.bytestream._02fileinputstream;


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

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/23 17:38
 **/

/*
Steps to read data
1.Create Input Stream Object
2.read Method Read Data
3.close
 */
public class Demo {
    public static void main(String[] args) throws IOException {
        //1. Create input stream objects
        FileInputStream in = new FileInputStream("a.txt");
        //2.read method reads data

        // read() Read a single byte return value represents read byte value readData
        //readSingle(in);

        // read(byte[]) Read data populated into the array return value represents the number of bytes read readCount
        byte[] bytes = new byte[1024];
        //readMulti(in, bytes);


        // read(byte[] ,int off,int len)
        int readCount2 = in.read(bytes, 1, 3);
        System.out.println(new String(bytes));

        //3.close
        in.close();
    }

    private static void readMulti(FileInputStream in, byte[] bytes) throws IOException {
        int readCount = in.read(bytes);
        System.out.println(readCount);

        // byte[] ---> String
        String s = new String(bytes, 0, readCount);
        System.out.println(s);
    }

    private static void readSingle(FileInputStream in) throws IOException {
        int readData1 = in.read();
        System.out.println(((char) readData1));

        int readData2 = in.read();
        System.out.println(((char) readData2));

        int readData3 = in.read();
        System.out.println(((char) readData3));

        int readData4 = in.read();
        System.out.println(readData4);
    }

}

 

package _17io01.com.cskaoyan.bytestream._02fileinputstream;

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

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/23 17:49
 **/

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Create Input Stream Object
        FileInputStream in = new FileInputStream("a.txt");
        //read
        byte[] bytes = new byte[4];
        int readCount1 = in.read(bytes);
        System.out.println(new String(bytes));
        // Printed results? abcd

        // Read again
        int readCount2 = in.read(bytes);
        System.out.println(new String(bytes,0,readCount2));
        // Print results
        //close
        in.close();
    }
}

 

Loop Read

package _17io.com.cskaoyan.bytestream._02fileinputstream;

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

/**
 * @description: Loop Read
 * @author: Sedum Sedum
 * @date: 2022/6/24 9:48
 **/

public class Demo3 {
    public static void main(String[] args) throws IOException {
        // Create Input Stream Object
        FileInputStream in = new FileInputStream("a.txt");
        // read
        // Simple method
        //readWhile1(in);


        // Advanced methods
        // Single Byte Read
        //readWhile2(in);


        // Read multiple bytes
        // Represents the number of bytes read
        int readCount;
        byte[] bytes = new byte[1024];
        while ((readCount = in.read(bytes)) != -1) {
            System.out.println(new String(bytes,0,readCount));
        }

        // close
        in.close();
    }

    private static void readWhile2(FileInputStream in) throws IOException {
        // Represents a byte value read
        int readData;
        while ((readData = in.read()) != -1) {
            System.out.println(((char) readData));
        }
    }

    private static void readWhile1(FileInputStream in) throws IOException {
        while (true) {
            int readData = in.read();
            if (readData == -1) {
                break;
            }
            System.out.println(((char) readData));
        }
    }
}

BufferedInputStream Buffered Byte Input Stream

Inheritance relationship

 

Construction method

BufferedInputStream(InputStream in) creates a BufferedInputStream and saves its parameters, the input stream in, for future use. Default is 8KB
BufferedInputStream(InputStream in, int size) creates a BufferedInputStream with a specified buffer size and saves its parameters, the input stream in, for future use. Buffer size is size

Member Method

3 Reads

package _17io.com.cskaoyan.bytestream._05bufferedinputstream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 11:12
 **/

public class Demo {
    public static void main(String[] args) throws IOException {
        // Create buffered input stream objects
        BufferedInputStream in =
                new BufferedInputStream(new FileInputStream("a.txt"));
        // read
        // Single byte
        int readData = in.read();
        System.out.println(readData);

        byte[] bytes = new byte[1024];
        int readCount = in.read(bytes);
        System.out.println(new String(bytes,0,readCount));

        // close
        in.close();

    }
}

File Copy Function

Ideas:

  • Read source files into memory

  • Write data to target file

 

Text file single byte 17ms multi-byte 0

Picture file single byte 1552ms multi-byte 3ms

Video file single byte 16885ms multi-byte 36ms

package _17io.com.cskaoyan.bytestream._03copy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description: File Copy
 * @author: Sedum Sedum
 * @date: 2022/6/24 10:03
 **/

public class Demo1 {
    public static void main(String[] args) throws IOException {
        // Create Input Stream Object
        //FileInputStream in = new FileInputStream("D:\\a.txt");
        //FileInputStream in = new FileInputStream("D:\\a.jpg");
        FileInputStream in = new FileInputStream("D:\\aa.mp4");
        // Create Output Stream Object
        //FileOutputStream out = new FileOutputStream("copy_a.txt");
        //FileOutputStream out = new FileOutputStream("copy_a.jpg");
        FileOutputStream out = new FileOutputStream("copy_aa.mp4");
        // Read and write
        // Single byte replication
        long start = System.currentTimeMillis();

        //copySingle(in, out);

        //Multibyte replication
        copyMulti(in, out);


        // copy complete
        long end = System.currentTimeMillis();
        System.out.println(end-start);

        // close releases resources
        in.close();
        out.close();
    }

    private static void copyMulti(FileInputStream in, FileOutputStream out) throws IOException {
        int readCount;
        byte[] bytes = new byte[1024];
        while ((readCount = in.read(bytes)) != -1) {
            // write
            out.write(bytes,0,readCount);
        }
    }

    private static void copySingle(FileInputStream in, FileOutputStream out) throws IOException {
        int readData;
        while ((readData = in.read()) != -1) {
            // write
            out.write(readData);
        }
    }
}

Is single byte or byte array efficient?

High byte array efficiency

Reason: Reduced interaction with the operating system

Give an example:

Suppose I bought 5 couriers and delivered them by express brothers in Jingdong, my home is 10 kilometers from the distribution station

Single byte: courier boy delivers one and five times at a time

Byte Array: Togo said we were all brothers and gave each brothers a BMW only once

Character Stream

Why is there a character stream?

Use byte streams to read English numbers -- > No problem

Using byte streams to read Chinese --->There may be a problem

How a character exists in a computer

According to an encoding table, a character that has an integer value in the encoding table stores the integer value (coded value)

Coding table

Common coding tables

ASCII: American Standard Information Exchange Code. Represented in 7 bits of a byte. 0000 0000 - 0111 1111 ISO8859-1: Latin code table. The European code table is represented by 8 bits of a byte. 0000 0000 - 1111 1111

GB2312: Chinese coding table for China. GBK: The Chinese coding table in China has been upgraded to incorporate more Chinese characters. An alternative version of GB18030:GBK, BIG-5 Code: a traditional word encoding scheme, commonly known as Big Five Code, that is used in Taiwan and Hong Kong.

Unicode: International standard code that combines multiple languages.

UTF-8: Variable length to represent a character. Unlike UTF-8, it defines an "interval rule" that maintains maximum compatibility with ASCII encoding:

It encodes Unicode as a character of 00000000-0000007F, 0111 1111 = 7F in a single byte, it encodes Unicode as a character of 00000080-000007FF in two bytes, and it encodes Unicode as a character of 00000800-0000FFFF in three bytes

1 byte 0xxxxxx 2 bytes 110xxxxx 10xxxxxx 3 bytes 1110xxxx 10xxxxx 10xxxx 10xxxx

utf-16:

Encoding table used by jvm, coded and decoded in 2 bytes

Char: 2 bytes

Commonly used in work (to meet)

ASCII

ISO8859-1

GBK: 2 bytes for a Chinese character

UTF-8: 3 bytes for a Chinese character

Codec

Code

  • Based on an encoding table, the process of storing string data - > binary data to a computer (what people understand - > what computers understand)

Decode

  • Reverse process of encoding. Based on an encoding table (what the computer understands-->what the human understands)

Chinese Coding Table You 0x0001

Japanese Coding Table 0x0001

Example: similar to Moss password

Codec in java

Default encoding table

  • Win GBK (value of ANSI default character set GBK)

  • idea utf-8

package _17io.com.cskaoyan.charstream._02encode;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @description: java Codec in
 * @author: Sedum Sedum
 * @date: 2022/6/24 15:03
 **/

public class Demo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "Hello";
        // Encoding process
        // Encoding with default character set
        //byte[] bytes = s.getBytes();
        //System.out.println(Arrays.toString(bytes));

        // Encoding using the specified character set
        // getBytes(String charsetName)
        // Encodes this String as a byte sequence using the specified character set and stores the result in a new byte array.
        byte[] bytes = s.getBytes("GBK");
        System.out.println(Arrays.toString(bytes));
        // Decoding process
        // Constructing method with String
        // String(byte[] bytes)
        // Constructs a new String by decoding the specified byte array with the platform's default character set.
        //String s1 = new String(bytes);
        //System.out.println(s1);

        // Decode using specified character set
        // String(byte[] bytes, String charsetName)
        //Constructs a new String by decoding the specified byte array with the specified charset.
        String s1 = new String(bytes,"gbk");
        System.out.println(s1);
    }
}

Reasons for garbled problems

  • Inconsistent encoding and decoding

How to Solve

  • Make it consistent

The nature of character flow

 

Character Output Stream

Abstract Base Class Writer

Writing abstract classes to character streams

Inheritance relationship

 

Member Method

voidwrite(char[] cbuf) writes an array of characters.
abstract voidwrite(char[] cbuf, int off, int len) writes to a part of the character array.
voidwrite(int c) writes a single character. The characters to be written are contained in 16 low bits of a given integer value, while 16 high bits are ignored.
voidwrite(String str) writes a string.
voidwrite(String str, int off, int len) writes to a part of the string.

Specific subclasses

OutputStreamWriter Conversion Stream

OutputStreamWriter is the bridge between character flow and byte flow: the specified charset Encode the characters to be written to the stream as bytes. The character set it uses can be specified by name or explicitly given, otherwise the platform default character set will be accepted.

Inheritance relationship

 

Construction method

OutputStreamWriter(OutputStream out) creates OutputStreamWriter with default character encoding.
OutputStream Writer (OutputStream out, String charsetName) creates an OutputStream Writer that uses the specified character set.

Member Method

voidwrite(char[] cbuf) writes an array of characters.
abstract voidwrite(char[] cbuf, int off, int len) writes to a part of the character array.
voidwrite(int c) writes a single character. The characters to be written are contained in 16 low bits of a given integer value, while 16 high bits are ignored.
voidwrite(String str) writes a string.
voidwrite(String str, int off, int len) writes to a part of the string.
package _17io.com.cskaoyan.charstream._03outputstreamwriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 15:53
 **/

public class Demo {
    public static void main(String[] args) throws IOException {
        // Create Output Stream Object
        OutputStreamWriter out =
                new OutputStreamWriter(new FileOutputStream("a.txt"));
        // write
        // write(int c)
        //out.write(97);

        // write(char[] c)
        //String s = "Bao, I transfused today, what night I transfused, think of you at night";
        //char[] chars = s.toCharArray();
        //out.write(chars);
        //out.write(System.lineSeparator());
        //
         write(chars[] c,int off ,int len)
        //out.write(chars,0,chars.length);

        // Character Output Stream-specific method for manipulating strings directly
        // write(String s)
        String s = "Treasure,I poached today,What stool,Think of you over and over";
        out.write(s);

        // write(String s,int off,int len)
        out.write(System.lineSeparator());
        out.write(s, 0, 5);
        // flush
        out.flush();
        // close
        out.close();
    }
}

FileWriter streamline

Convenient class for writing character files

Inheritance relationship

 

Construction method

FileWriter(File file) constructs a FileWriter object from a given File object.
FileWriter(File file, boolean append) constructs a FileWriter object from a given File object.
FileWriter(String fileName) constructs a FileWriter object from a given file name.
FileWriter(String fileName, boolean append) constructs a FileWriter object based on a given file name and a boolean value indicating whether to attach the written data.

Member Method

5 writes = 3 + 2

voidwrite(char[] cbuf) writes an array of characters.
abstract voidwrite(char[] cbuf, int off, int len) writes to a part of the character array.
voidwrite(int c) writes a single character. The characters to be written are contained in 16 low bits of a given integer value, while 16 high bits are ignored.
voidwrite(String str) writes a string.
voidwrite(String str, int off, int len) writes to a part of the string.
package _17io.com.cskaoyan.charstream._06simple;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 16:25
 **/

public class Demo {
    public static void main(String[] args) throws IOException {
        // Create Output Stream Object
        FileWriter fileWriter = new FileWriter("a.txt");
        // Write data
        fileWriter.write("Treasure,You're a little strange today,Strange and lovely");

        // flush
        fileWriter.flush();
        // close
        fileWriter.close();
    }
}

BufferedWriter Buffer Stream

Writes text to the character output stream, buffering individual characters, thereby providing efficient writing of individual characters, arrays, and strings.

You can specify the size of the buffer or accept the default size

Inheritance relationship

 

Construction method

BufferedWriter(Writer out) creates a buffer character output stream that uses a default size output buffer. Default is 16KB
BufferedWriter(Writer out, int sz) creates a new buffer character output stream that uses a given size output buffer.

Member Method

5+1 = 5 writes + 1 method of its own

voidnewLine() writes a line separator.
voidwrite(char[] cbuf) writes an array of characters.
abstract voidwrite(char[] cbuf, int off, int len) writes to a part of the character array.
voidwrite(int c) writes a single character. The characters to be written are contained in 16 low bits of a given integer value, while 16 high bits are ignored.
voidwrite(String str) writes a string.
voidwrite(String str, int off, int len) writes to a part of the string.
package _17io.com.cskaoyan.charstream._07buffer;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 16:41
 **/

public class Demo {
    public static void main(String[] args) throws IOException {
        // Create Output Stream Object
        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
        // write
        bw.write("Treasure,Do you know why I like fish heads??For the rest of your life");
        
        // newLine()
        bw.newLine();
        bw.write("gun");
        // flush
        bw.flush();
        // close
        bw.close();
    }
}

Character input stream

Abstract Base Class Reader

An abstract class for reading character streams

Inheritance relationship

 

Member Method

intread() reads a single character. Characters read as integers, ranging from 0 to 65535 (0x00-0xffff), returning -1 readData if the end of the stream has been reached
intread(char[] cbuf) reads characters into an array. Number of characters read, returns -1 readCount if the end of the stream has been reached
abstract intread(char[] cbuf, int off, int len) reads a character into a part of the array.

Specific subclasses

InputStreamReader Conversion Stream

InputStreamReader is the bridge between byte flow and character flow: it uses the specified charset Reads bytes and decodes them into characters. The character set it uses can be specified by name or explicitly given, or it can accept the platform default character set

Inheritance relationship

 

Construction method

InputStreamReader(InputStream in) creates an InputStreamReader that uses the default character set.
InputStreamReader(InputStream in, String charsetName) creates an InputStreamReader that uses the specified character set.

Member Method

Three read methods are identical to the parent

intread() reads a single character. Characters read as integers, ranging from 0 to 65535 (0x00-0xffff), returning -1 readData if the end of the stream has been reached
intread(char[] cbuf) reads characters into an array. Number of characters read, returns -1 if the end of the stream has been reached
abstract intread(char[] cbuf, int off, int len) reads a character into a part of the array.
package _17io.com.cskaoyan.charstream._04inputstramreader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 16:07
 **/

public class Demo {
    public static void main(String[] args) throws IOException {
        // Create Input Stream Object
        InputStreamReader in = new InputStreamReader(new FileInputStream("a.txt"));
        // read
        // read()
        int readData = in.read();
        System.out.println(((char) readData));
        // read(char[] c)
        char[] chars = new char[1024];
        // Number of characters read
        int readCount = in.read(chars);
        System.out.println(new String(chars,0,readCount));
        // close
        in.close();
    }
}

FileReader streamline

Convenient class for reading character files

Inheritance relationship

 

Construction method

FileReader(File file)

FileReader(String filename)

Member Method

3 Reads

intread() reads a single character. Characters read as integers, ranging from 0 to 65535 (0x00-0xffff), returning -1 readData if the end of the stream has been reached
intread(char[] cbuf) reads characters into an array. Number of characters read, returns -1 readCount if the end of the stream has been reached
abstract intread(char[] cbuf, int off, int len) reads a character into a part of the array.
package _17io.com.cskaoyan.charstream._06simple;

import java.io.FileReader;
import java.io.IOException;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 16:30
 **/

public class Demo2 {
    public static void main(String[] args) throws IOException {

        // Create Input Stream Object
        FileReader reader = new FileReader("a.txt");
        // read
        char[] chars = new char[1024];
        int readCount = reader.read(chars);
        System.out.println(new String(chars,0,readCount));
        // close
        reader.close();
    }
}

Conversion Flow VS Simplified Flow

  • From the perspective of inheritance relationship, transformed streams are parent classes and simplified streams are subclasses

  • From a usage point of view, converting streams is cumbersome and simplifying streams is convenient

  • The biggest difference is that Conversion Streams specify character sets, simplifying streams doesn't work

BufferedReader Buffer Stream

Reads text from a character input stream, buffering individual characters, thereby enabling efficient reading of characters, arrays, and rows.

You can specify the size of the buffer, or you can use the default size

Inheritance relationship

 

Construction method

BufferedReader(Reader in) creates a buffer character input stream that uses the default size input buffer. Default 16KB
BufferedReader(Reader in, int sz) creates a buffer character input stream using a specified size input buffer.

Member Method

3+1 = 3 read methods, 1 method of its own

StringreadLine() reads a line of text.
String containing the contents of the line, without any line terminators, returns null if the end of the stream has been reached
package _17io01.com.cskaoyan.charstream._07buffer;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/24 17:15
 **/

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Create Input Stream Object
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        // readLine
        //read1(br);
        
        // Loop Read
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        // close
        br.close();
    }

    private static void read1(BufferedReader br) throws IOException {
        String s = br.readLine();
        System.out.println(s);
        String s1 = br.readLine();
        System.out.println(s1);
        String s2 = br.readLine();
        System.out.println(s2);
    }
}

Other streams

data stream

Write integer 1000 decimal 3.14 in byte flow file

Conclusion: No

DataOutputStream Data Output Stream

Data output streams allow applications to write basic Java data types to the output stream in an appropriate manner. The application can then read data in using data input streams.

Inheritance relationship

 

Construction method

DataOutputStream(OutputStream out) creates a new data output stream that writes data to the specified base output stream.

Member Method

Each java basic data type has a corresponding write method

Give an example:

writeInt(int a)

writeDouble(double a)

....

package _18io02.com.cskaoyan.otherstream._01datastream;

import java.io.*;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/25 9:45
 **/

public class Demo2 {
    public static void main(String[] args) throws IOException {
        writeData();
        readData();
    }

    private static void readData() throws IOException {
        // Create Data Input Stream Object
        DataInputStream in = new DataInputStream(new FileInputStream("a.txt"));
        // read
        int i = in.readInt();
        System.out.println(i);

        double v = in.readDouble();
        System.out.println(v);

        // close
        in.close();
    }

    private static void writeData() throws IOException {
        // Create Data Output Stream Object
        DataOutputStream out = new DataOutputStream(new FileOutputStream("a.txt"));
        // write
        // int 1000
        out.writeInt(1000);
        // double 3.14
        out.writeDouble(3.14);
        // close
        out.close();
    }
}

DataInputStream Data Input Stream

Data input streams allow applications to read basic Java data types from underlying input streams in a machine-independent manner

Inheritance relationship

 

Construction method

DataInputStream(InputStream in) creates a DataInputStream using the specified underlying InputStream.

Member Method

Each java basic data type has a corresponding read method

Give an example:

readInt()

readDouble()

....

 

package _18io02.com.cskaoyan.otherstream._01datastream;
import java.io.*;
/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/25 9:57
 **/

public class Demo3 {
    public static void main(String[] args) throws IOException {
        write();
        read();
    }

    private static void read() throws FileNotFoundException, IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));
        byte b = dis.readByte();
        System.out.println(b);
        short s = dis.readShort();
        System.out.println(s);
        int i = dis.readInt();
        System.out.println(i);
        long l = dis.readLong();
        System.out.println(l);
        float f = dis.readFloat();
        System.out.println(f);
        double d = dis.readDouble();
        System.out.println(d);
        char ch = dis.readChar();
        System.out.println(ch);
        boolean bb = dis.readBoolean();
        System.out.println(bb);
        dis.close();
    }

    private static void write() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));
        dos.writeByte(1);
        dos.writeShort(20);
        dos.writeInt(300);
        dos.writeLong(4000);
        dos.writeFloat(12.34f);
        dos.writeDouble(12.56);
        dos.writeChar('a');
        dos.writeBoolean(true);
        dos.close();
    }
}

Be careful:

  • Write in what order read in the same order

Print Stream

Core Ideas:

Different types of data are converted to strings, --> is written as strings

Practice:

Define a class Printer

Define member variable OutputStream out;

Provide five methods

Data publice void writeInt(int a) {} written specifically to the file with type int

Write data of type int specifically to the file and wrap publice void writeIntLn(int a){}

Data publice void writeDouble(double a) {} written specifically to a file with a double type

Write data of type double specifically to the file and wrap publice void writeDoubleLn(double a){}

Method for releasing resources public void close(){}

package _18io02.com.cskaoyan.otherstream._02printstream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/25 10:05
 **/

/*
Practice:
Define a class Printer
 Define member variable OutputStream out;
Provide five methods
 Data publice void writeInt(int a) {} written specifically to the file with type int
 Write data of type int specifically to the file and wrap publice void writeIntLn(int a){}
Data publice void writeDouble(double a) {} written specifically to a file with a double type
 Write data of type double specifically to the file and wrap publice void writeDoubleLn(double a){}
Method for releasing resources public void close(){}
 */
public class Demo {
    public static void main(String[] args) throws IOException{
        // Create Printer Object
        Printer printer = new Printer(new FileOutputStream("a.txt"));
        // Write int
        printer.writeIntLn(1000);
        // Write double
        printer.writeDouble(3.14);
        // Release Resources
        printer.close();
    }
}

class Printer{
    // Member variables
    OutputStream out;
    public Printer(OutputStream out) {
        this.out = out;
    }
    //Provide five methods
    //
    //Data publice void writeInt(int a) {} written specifically to the file with type int
    public void writeInt(int a) throws IOException {
        // Conversion of data types
        // int --->String
        String s = String.valueOf(a);
        out.write(s.getBytes());
    }
    //Write data of type int specifically to the file and wrap publice void writeIntLn(int a){}
    public void writeIntLn(int a) throws IOException {
        // Conversion of data types
        // int --->String
        String s = String.valueOf(a);
        out.write(s.getBytes());
        // Line Break
        out.write(System.lineSeparator().getBytes());
    }

    //Data publice void writeDouble(double a) {} written specifically to a file with a double type
    public void writeDouble(double a) throws IOException {
        // double ---> String
        String s = String.valueOf(a);
        out.write(s.getBytes());

    }
    //Write data of type double specifically to the file and wrap publice void writeDoubleLn(double a){}
    public void writeDoubleLn(double a) throws IOException {
        // double ---> String
        String s = String.valueOf(a);
        out.write(s.getBytes());
        // Line Break
        out.write(System.lineSeparator().getBytes());
    }
    //Method for releasing resources public void close(){}
    public void close() throws IOException {
        out.close();
    }
}

PrintStream Byte Print Stream

PrintStream adds functionality to other output streams so that they can easily print various data value representations

Inheritance relationship

 

Construction method

PrintStream(File file) creates a refreshed print stream with the specified file and without automatic line refresh.
PrintStream(OutputStream out) creates a new print stream.
PrintStream(OutputStream out, boolean autoFlush) creates a new print stream.
PrintStream(String fileName) creates a refreshed print stream with the specified file name without automatic line refresh.

Member Method

Each basic data type has a print method corresponding to it

Print int print(int a)

Print double print(double)

PrintWriter Character Print Stream

A formatted representation of an object printed to a text output stream

Inheritance relationship

 

Construction method

PrintWriter(File file) uses the specified file to create a new PrintWriter without automatic line refresh.
PrintWriter(OutputStream out) creates a refresh PrintWriter from an existing OutputStream without automatic line refresh.
PrintWriter(OutputStream out, boolean autoFlush) creates a new PrintWriter from an existing OutputStream.
PrintWriter(String fileName) creates a refresh PrintWriter with the specified file name without automatic line refresh.
PrintWriter(Writer out) creates a new PrintWriter without automatic line refresh.
PrintWriter(Writer out, boolean autoFlush) creates a new PrintWriter.

Member Method

Each basic data type has a print method corresponding to it

Print int print(int a)

Print double print(double)

Four Features of Print Stream

  1. You can only operate on destinations, not data sources.

    1. No one input stream corresponds to it, and all byte character print streams are output streams

  2. You can manipulate any type of data.

    1. Convert different types of data into strings, written as strings (String.valueOf(int....))

  3. If automatic refresh is started, it can be refreshed automatically.

    1. As a precondition, if automatic refresh is enabled, this operation can only be completed if one of the methods of println, printf, or format is called

    2.  

    3.  

  4. Streams that can manipulate files

    • Constructor can pass File objects or String fileName

Standard input-output stream

  • Standard Output Stream

    • System.out

    • Essential: PrintStream type byte print stream

    • Default Output Device: Display

  • Standard input stream

    • System.in

    • Essential: InputStream normal byte input stream

    • Default input device: keyboard

Practice:

Use System.in simulates nextLine inside Scanner

Ideas:

There is a method readLine in BufferedReader

package _18io02.com.cskaoyan.otherstream._02printstream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/25 11:06
 **/

/*
Practice:

Use System.in simulates nextLine inside Scanner

Ideas:

BufferedReader There is a method readLine inside
 */
public class Ex {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // Implement functionality using readLine method
        //String s = br.readLine();
        //System.out.println(s);
        //br.close();

        // Modifying requirements requires multiple keyboard inputs
        // while
        //String line;
        //while ((line = br.readLine()) != null) {
        //    System.out.println(line);
        //}

        // How to Solve End Loop
        // By an end tag such as "gun"
        while (true) {
            String s = br.readLine();
            // judge
            if ("gun".equals(s)) {
                break;
            }
            System.out.println(s);
        }


        br.close();
    }
}

Object Flow (Serialization and Deserialization Flow)

Student s = new Student("zs",20);

What is serialization and deserialization?

  • serialize

    • The process of converting object data to binary data persistent storage

  • Deserialize

    • Restore binary data back to object data

ObjectOutputStream Serialized Stream

ObjectOutputStream writes basic data types and graphics of Java objects to OutputStream. ObjectInputStream can be used to read (refactor) objects. Persistent storage of objects is achieved by using files in streams. If the stream is a network socket stream, objects can be refactored on another host or in another process.

Only Java will be supported. Io. Objects for Serializable interface are written to the stream

Serializable is an empty interface that acts as a marker

Inheritance relationship

 

Construction method

ObjectOutputStream(OutputStream out) creates an ObjectOutputStream that is written to the specified OutputStream.

Member Method

voidWteObject (Object obj) writes the specified object to ObjectOutputStream.

ObjectInputStream Deserialized Stream

ObjectInputStream deserializes basic data and objects previously written using ObjectOutputStream

Inheritance relationship

 

Construction method

ObjectInputStream(InputStream in) creates an ObjectInputStream read from the specified InputStream.

Member Method

ObjectreadObject() Reads an object from ObjectInputStream

Demo

package _18io02.com.cskaoyan.otherstream._03objectstream;

import java.io.*;

/**
 * @description:
 * @author: Sedum Sedum
 * @date: 2022/6/25 11:25
 **/

public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Serialization process
        serialize();

        // Deserialization process
        unSerialize();
    }

    private static void unSerialize() throws IOException, ClassNotFoundException {
        // Create Input Stream Object
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("b.txt"));
        // readObject()
        Object o = in.readObject();
        System.out.println(o);
        // close
        in.close();
    }

    private static void serialize() throws IOException {
        // Save Student Object to File
        // Create Student Object
        //Student student = new Student (Zhang San, 20);
        Student student = new Student("Zhang San", 20, true, 59);

        // Create Output Stream Object
        ObjectOutputStream out =
                new ObjectOutputStream(new FileOutputStream("b.txt"));

        // writeObject(Object obj)
        out.writeObject(student);
        // close
        out.close();
    }
}

// Define Student Classes
class Student implements Serializable {
    // Member variables
    String name;
    int age;
    boolean gender;
    static final long serialVersionUID = 42L;
    // transient modifies variables that do not want to be serialized
    transient int score;

    public Student(String name, int age, boolean gender, int score) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.score = score;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String name, int age, boolean gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    //@Override
    //public String toString() {
    //    return "Student{" +
    //            "name='" + name + '\'' +
    //            ", age=" + age +
    //            '}';
    //}

    //@Override
    //public String toString() {
    //    return "Student{" +
    //            "name='" + name + '\'' +
    //            ", age=" + age +
    //            ", gender=" + gender +
    //            '}';
    //}

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                ", score=" + score +
                '}';
    }
}

Be careful:

  • java.io.NotSerializableException class does not implement Serializable interface

  • Java. Io. InvalidClassException: 18io02. Com. Cskaoyan. Otherstream. 03objectstream. Student; Local class incompatible: stream classdesc serialVersionUID = -516721902453857, local class serialVersionUID = -66914807092677264 SerialVersionUID does not match

  • // Modify variables that you do not want to be serialized
    transient 

Summary!

typeByte Output StreamByte Input StreamCharacter Output StreamCharacter input stream
Abstract Base ClassOutputStreamInputStreamWriterReader
File correlationFileOutputStreamFileInputStreamFileWriterFileReader
Buffer correlationBufferedOutputStreamBufferedInputStreamBufferedWriterBufferedReader
Conversion correlationOutputStreamWriterInputStreamReader
Data correlationDataOutputStreamDataInputStream
Print RelatedPrintStreamPrintWriter
Object RelevanceObjectOutputStreamObjectInputStream

Tags: Java JavaSE intellij-idea

Posted by serbestgezer on Sun, 03 Jul 2022 02:54:16 +0930