This is the 24th day of my participation in the August More Text Challenge

IO flow profile

Input/Output is referred to as IO. Java abstracts the input and output of data into a stream, which is a sequential, one-way collection of data with a beginning and an end.

The classification of the flow

According to the flow direction, the flow can be divided into input flow and output flow.

  • Input stream: Data can only be read from, not written to.
  • Output stream: Data can only be written to, not read from.
  • JavaThe input stream is mainly composed ofInputStreamReaderAs the base class, while the output stream is dominated byOutputStreamWriterAs a base class. These are abstract base classes that cannot create instances directly.

According to the data unit of operation, it can be divided into byte stream and character stream.

  • Byte streams and character streams are used almost exactly the same, the difference being the data units that byte streams and character streams operate on.
  • The data unit of byte stream operation is8The byte of bits, while the data unit of the character stream operation is16Bit characters.
  • The byte stream is mainly composed ofInputStreamOutputStreamAs a base class, while character streams are dominated byReaderWriterAs a base class.

Flows can be divided into node flows and processing flows according to their roles.

  • Can be from/to a specificIOA stream of data read/written by a device (such as a disk or network) is calledThe node flow, node flow is also known asLow flow(Low Level Stream). When using node streams for input/output, the program connects directly to the actual data source and to the actual input/output node.
  • A processing stream is used to connect or encapsulate an existing stream, and the encapsulated stream is used to implement data read/write functions. Processing flows are also referred to as advanced flows. When using a processing stream for input/output, the program does not connect directly to the actual data source and does not connect to the actual input/output node.
  • JavaWrapping node flows with processing flows is a typical decorator design pattern. Wrapping different node flows with processing flows both eliminates implementation differences between different node flows and provides a more convenient way to accomplish input/output functions. So the processing stream is also calledPacking flow.

The File type

The File class is an abstract representation of File and directory pathnames. It has the following common methods.

exists()

  • Tests whether the file or directory represented by this abstract pathname exists and returns if it doestrueOtherwise returnfalse.

createNewFile()

  • Check if the file exists, and atomically create a new empty file if it doesn’t.
  • Returns a Boolean value if the file does not exist and was successfully createdtrueOtherwise returnfalse.
  • Throw aIOExceptionabnormal

delete()

  • Deletes the file or directory represented by this abstract pathname. If this pathname represents a directory, the directory must be empty to be deleted.
  • When files cannot be deleted,deleteMethod throwsIOExceptionThis is useful for error reporting and diagnosing why files cannot be deleted.
  • Returns when a file or directory is successfully deletedtrueOtherwise returnfalse

isDirectory()

  • Tests whether the file represented by this abstract pathname is a directory.
  • If it is a directory, returntrueOtherwise returnfalse

length()

  • Returns the length represented by this abstract pathname. If this pathname represents a directory, the return value is not specified.
  • Returns the file length of typelongIf the file does not exist, return0L.

listFiles()

  • If the abstract pathname represents a directory, return the value specified byFileAn array of objects; Returns if a file is representednull.

mkdir()

  • Create a directory named after this abstract pathname.
  • Returns if the directory was successfully createdtrueOtherwise returnfalse.

renameTo()

  • To receive aFileObject to rename the original file to the specified file.
  • Returns if the rename succeededtrueOn failure, returnfalse.
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class IOTest {
    public static void main(String[] args) {
        File file = new File("test");
        // Whether the file exists
        boolean exists = file.exists();
        System.out.println("exists: " + exists);
        // Create a file
        if(! exists) {try {
                boolean created = file.createNewFile();
                System.out.println("created: " + created);
            } catch(IOException e) { e.printStackTrace(); }}// Check the file length
        long len = file.length();
        System.out.println("length: " + len);
        / / renamed
        boolean rename = file.renameTo(new File("hello"));
        System.out.println("rename: " + rename);
        // Delete files
        boolean delete = file.delete();
        System.out.println("delete: " + delete);
        // Check whether it is a folder
        File dir = new File("dir");
        boolean isDir = dir.isDirectory();
        System.out.println("dir: " + isDir);
        if (isDir) {
            File[] files = dir.listFiles();
            System.out.println(Arrays.toString(files));
        }
        /* exists: false created: true length: 0 rename: false delete: true dir: true [dir\a, dir\b, dir\subdir] */}}Copy the code

FileInputStream reads binary files

FileInputStream inherits from InputStream, which gets an InputStream from a file.

FileInputStream is primarily used to read binary streams. If you want to read streams of characters, you should use FileReader.

Common construction methods:

  • FileInputStream(File file): Receive aFileobject
  • FileInputStream(String name): Receives a string representing the path of the file

Common methods:

  • read(): Reads one byte of data from the input stream and returns oneintType, returned if read to the end of the file- 1.
  • read(byte[] b): Receives an array of bytes, read from the input streamb.lengthOne byte of data into a byte array. Returns aintType, representing the total number of bytes read, returned when the end of the file is reached- 1.
  • close(): Closes the file input stream and releases all system resources related to the file input stream. This method has no return value.
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamTest {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("hello");
            int i = fis.read();
            System.out.println(i); / / 97
            i = fis.read();
            System.out.println(i); / / 98
            i = fis.read();
            System.out.println(i); / / 99
            i = fis.read();
            System.out.println(i); // -1
        } catch(IOException e) { e.printStackTrace(); }}}Copy the code

InputStreamReader reads text files

InputStreamReader is a byte stream to a character stream that reads bytes and decodes them into characters using a specified character set. The character set it uses can be specified by name, given explicitly, or it can use the platform’s default character set.

Each time InputStreamReader’s read() method is called, one or more bytes are read from the byte stream. In order to efficiently convert bytes to characters, it is possible to read more bytes in advance than is needed for the current read() operation.

For best performance, you can wrap InputStreamReader with BufferedReader. Such as:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Copy the code

Common methods:

  • getEncoding(): returns a string representing the character encoding used by the current input stream, for example"UTF8".
  • read(): Reads a single character (of typeint), returns if the end of the stream is reached- 1That will be thrownIOExceptionThe exception.
  • read(char[] cbuf, int offset, int length): reads a portion of the stream into the target array.cbufIs the target array,offsetSpecifies where to start storing characters,lengthIs the most characters read. Returns the number of characters read, or if the end of the stream is reached- 1.
  • close(): Closes the stream and frees all system resources associated with it. Called when the stream is closedread(),ready(),mark(),reset()orskip()throwIOExceptionThe exception. Closing a previously closed stream has no effect.

Sample code:

Hello, hello.

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

public class InputStreamReaderTest {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("hello");
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        System.out.println(inputStreamReader.getEncoding()); // UTF8
        int c = inputStreamReader.read();
        System.out.println(c); / / 20320
        char[] charArr = new char[10];
        int readed = inputStreamReader.read(charArr, 0.10);
        System.out.println(Arrays.toString(charArr)); // [ok, ah,,,,,,,,]
        System.out.println(readed); / / 2fileInputStream.close(); }}Copy the code

BufferedReader reads text files

BufferedReader reads text from the character input stream, buffering characters to provide efficient reads of characters, arrays, and lines. The buffer size can be specified, but the default size is sufficient for most purposes.

Typically, a read request from a Reader results in a read request from the corresponding underlying byte stream and character stream. Therefore, it is recommended to use BufferedReader to wrap any expensive readers (such as FileReader and InputStreamReader).

Example:

BufferedReader in = new BufferedReader(new FileReader("foo.in"));
Copy the code

Without buffering, each call to read() or readLine() causes bytes to be read from the file, converted to characters, and then returned, which is expensive.

Sample code:

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

public class BufferedReaderTest {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("hello");
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = bufferedReader.readLine();
        System.out.println(line); / / how are you
        intc = bufferedReader.read(); System.out.println(c); }}Copy the code

The resources

  • crazyJavaThe notes
  • Oracle Java tutorial
  • JDK 8manual