Java file streaming and I/O

Posted by JamesyBHOY on Sat, 26 Feb 2022 14:10:54 +0100

Java file streaming and I/O

file

concept

  1. A file is where data is stored.
  2. File stream: files are operated in the form of stream in the program.
  3. Stream: the path of data between the data source (file) and the program (memory)
  4. Input stream: the path of data from data source (file) to program (memory)
  5. Output stream: the path of data from program (memory) to data source (file)

Common operation

create a file

  1. new File(String pathname) / / build a File object according to the path
  2. new File(File parent, String child) / / build according to the parent directory file + child path
  3. new File(String parent, String child) / / build according to the parent directory + word path
  4. createNewFile create a new file
		@Test
    public void creatFile01() {
        File file = new File("/Users/xinyu/Desktop/self-taught/Java/newFile.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void createFile02() {
        File parentPath = new File("/Users/xinyu/Desktop/self-taught/Java");
        String childName = "newFile01.txt";
        File file = new File(parentPath, childName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void createFile03() {
        String parentPath = "/Users/xinyu/Desktop/self-taught/Java";
        String childName = "newFile02.txt";
        File file = new File(parentPath, childName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Get file information

  1. getName
  2. getAbsolutePath
  3. getParent
  4. length
  5. exists
  6. isFile
  7. isDirectory
// Get file information
public static void info() {
    File file = new File("/Users/xinyu/Desktop/self-taught/Java/newFile.txt");
    // Call the corresponding file methods and properties
    System.out.println("File name:" + file.getName());
    System.out.println("Absolute path to file:" + file.getAbsolutePath());
    System.out.println("Parent directory of file:" + file.getParent());
    System.out.println("file size(byte): " + file.length());
    System.out.println("Whether the file exists:" + file.exists());
    System.out.println("Whether the file is a file:" + file.isFile());
    System.out.println("Whether the file is a directory:" + file.isDirectory());
}

Other operations

  1. mkdir create a first level directory
  2. mkdirs create multi-level directory
  3. delete deletes an empty directory or file
@Test
public void f1() {
    String path = "/Users/xinyu/Desktop/self-taught/Java/newFile.txt";
    File file = new File(path);
    if (file.exists()) {
        boolean delete = file.delete();
        if (delete) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("File deletion failed");
        }
    } else {
        System.out.println("The file does not exist");
    }
}

@Test
public void f2() {
    String path = "/Users/xinyu/Desktop/self-taught/Java/JavaTest";
    File file = new File(path);
    if (file.exists()) {
        System.out.println("The directory already exists");
    } else {
        if (file.mkdirs()) { // Create a multi-level directory mkdir create a one-level directory
            System.out.println("Directory created successfully");
        } else {
            System.out.println("Directory creation failed");
        }
    }
}

IO stream principle and stream classification

  1. According to different operation data units, it is divided into: byte stream (8bit) -- binary file, character stream (character) -- text file

  2. According to the flow direction of data flow, it is divided into input flow and output flow

  3. According to the different roles of flow, it can be divided into node flow, processing flow / packaging flow

  4. Abstract base classByte streamCharacter stream
    Input streamInputStreamReader
    Output streamOutputStreamWriter

Node flow and processing (packaging) flow

  1. Node flow: data can be read from a characteristic data source. For example: FileReader, FileWriter, FileInputStream, FileOutputStream
  2. Processing flow: "connect" the existing flow (processing flow or node flow) to provide more powerful reading and writing functions for the program. For example: BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream, ObjectReader, ObjectWriter, ObjectInputStream, ObjectOutputStream
  3. The data source is mainly for the place where the data is placed. If the file is a node stream, the processing stream is selected for other forms.
  4. BufferedReader has the attribute Reader, so it can wrap or encapsulate a node flow, which can be any Reader subclass.

Differences and connections

  1. Node flow is the bottom flow / low-level flow, which is directly connected with the data source
  2. Processing flow wrapping node flow can not only eliminate the implementation differences of different node flows, but also provide more convenient methods to realize input and output
  3. The processing flow wraps the node flow and uses the decorator design pattern, which will not be directly connected with the data source
  4. The processing stream increases the cache to improve the performance and improve the efficiency of input and output
  5. Processing flow may provide a series of convenient methods to input and output large quantities of data at one time, which is more flexible and convenient to use

Input stream

InputStream

FileInputStream file byte input stream

// The efficiency of reading a single byte is low
@Test
public void readFile01() {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test01.txt"; // File path
    FileInputStream fileInputStream = null;
    int readData = 0;
    try {
        // Create FileInputStream to read files
        fileInputStream = new FileInputStream(filePath);
        while ((readData = fileInputStream.read()) != -1) {
            System.out.print((char) readData);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Test
public void readFile02() {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test01.txt"; // File path
    FileInputStream fileInputStream = null;
    // Byte array definition
    byte[] buf = new byte[8]; // Read 8 bytes at a time
    int readLen = 0;
    try {
        // Create FileInputStream to read files
        fileInputStream = new FileInputStream(filePath);
        while ((readLen = fileInputStream.read(buf)) != -1) {
            String readDate = new String(buf, 0, readLen); // Note: during conversion, buf will not empty the array, so Len needs to be added
            System.out.print(readDate);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedInputStream buffered byte input stream

ObjectInputStream object byte input stream

Reader

FileReader

@Test
public void readFile01() {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test01.txt";
    FileReader fileReader = null;
    char ch = ' ';
    try {
        fileReader = new FileReader(filePath);
        // Single character reading
        while ((ch = (char) fileReader.read()) != -1) {
            System.out.print(ch);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Test
public void readFile02() {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test01.txt";
    FileReader fileReader = null;
    char[] cbuf = new char[8];
    int readLen = 0;
    try {
        fileReader = new FileReader(filePath);
        // Multiple character reading
        while ((readLen = fileReader.read(cbuf)) != -1) {
            System.out.print(new String(cbuf, 0, readLen));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedReader

ObjectReader

public class ObjectInputStream01 {
    public static void main(String[] args) {
        String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test04.dat";
        ObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream(filePath));
            // Deserialization of data in the same order as the deserialization (1)
            // 2. If not, there will be exceptions
            System.out.println(objectInputStream.readInt());
            System.out.println(objectInputStream.readBoolean());
            System.out.println(objectInputStream.readChar());
            System.out.println(objectInputStream.readDouble());
            System.out.println(objectInputStream.readUTF());
            try {
                Object obj = objectInputStream.readObject();
                System.out.println("Operation type=" + obj.getClass());
                System.out.println(obj);
                // If you need to call the method of the object Object(Dog), you need to turn down the line, so you need to use the Dog class
                // The Dog class needs to be applied together
                /*
                Dog dog = (Dog) obj;
                 */
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

class Dog implements Serializable {
    private String name;
    private int age;

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

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

InputStreamReader

  1. InputStreamReader: subclass of Reader, which can wrap (convert) InputStream (byte stream) into Reader (character stream)
public static void main(String[] args) throws IOException {
        String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test03.txt";
        FileInputStream fileInputStream = new FileInputStream(filePath);
        // 1. Convert FileInputStream byte stream to InputStreamReader byte stream,
        // 2. Add coding format
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
//        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "gbk");
        // 3. Transfer InputStreamReader into BufferedReader
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        System.out.println(bufferedReader.readLine());
        bufferedReader.close();  // Just turn off the outer flow
//        inputStreamReader.close();
//        fileInputStream.close();
    }

Output stream

OutputStream

FileOutputStream file byte output stream

@Test
public void writeFile01() {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test02.txt"; // File path
    FileOutputStream fileOutputStream = null;

    try {
        fileOutputStream = new FileOutputStream(filePath);
        fileOutputStream.write('a');

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Test
public void writeFile02() {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test02.txt"; // File path
    FileOutputStream fileOutputStream = null;
    String data = "hello world";
    byte[] bytes = data.getBytes();

    try {
        // 1. In this way, new FileOutputStream(filePath) will be overwritten when writing
        // 2. new FileOutputStream(filePath, true) is appended after this file
        fileOutputStream = new FileOutputStream(filePath, true);
        fileOutputStream.write(bytes);
        fileOutputStream.write(bytes, 1, 5); // Offset write

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedOutputStream buffered byte output stream

ObjectOutputStream object byte output stream

public class ObjectOutputStream01 {
    public static void main(String[] args) {
        // After. dat is serialized, it is not a plain text file, but in its own file content format
        String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test04.dat";
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
            objectOutputStream.writeInt(100); //Int - > integer implements the Serializable interface
            objectOutputStream.writeBoolean(true);
            objectOutputStream.writeChar('c');
            objectOutputStream.writeDouble(99.321);
            objectOutputStream.writeUTF("wxywxywxy");
            // Save object
            Dog dog = new Dog("wangcai", 3);
            objectOutputStream.writeObject(dog);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class Dog implements Serializable {
    private String name;
    private int age;

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

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

Writer

FileWriter

@Test
public void writeFile01() {
    FileWriter fileWriter = null;
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test02.txt";
    try {
        fileWriter = new FileWriter(filePath, true);
        String str = "Will there be a rainbow after the storm?";
        fileWriter.write(str);
        fileWriter.write(str, 1, 6);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileWriter.close(); // Write must be closed or refreshed, otherwise it will not be written
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Test
public void writeFile02() {
    FileWriter fileWriter = null;
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test02.txt";
    try {
        fileWriter = new FileWriter(filePath, true);
        String str = "   Will there be a rainbow after the storm?";
        fileWriter.write(str.toCharArray(), 0, 10);
        fileWriter.write(str.toCharArray());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileWriter.close(); // Must write close or refresh flush(), otherwise it will not be written!!!
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedWriter

ObjectWriter

public class ObjectOutputStream01 {
    public static void main(String[] args) {
        // After. dat is serialized, it is not a plain text file, but in its own file content format
        String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test04.dat";
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
            objectOutputStream.write(100); //Int - > integer implements the Serializable interface
            objectOutputStream.writeBoolean(true);
            objectOutputStream.writeChar('c');
            objectOutputStream.writeDouble(99.321);
            objectOutputStream.writeUTF("wxywxywxy");
            // Save object
            Dog dog = new Dog("wangcai", 3);
            objectOutputStream.writeObject(dog);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class Dog implements Serializable {
    private String name;
    private int age;

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

Considerations for object processing flow

  1. Read and write in the same order
  2. Serializable interface is required to realize serialization or deserialization
  3. SerialVersionUID is recommended to be added to serialized classes to improve version compatibility
  4. When serializing an object, all attributes in it are serialized by default, except for members decorated with static or transient
  5. When serializing an object, the data type of the attribute inside also needs to implement the serialization interface
  6. Serialization has inheritance, that is, if a class has implemented serialization, all its subclasses have implemented serialization by default

Copy

Copy binaries

public class FileCopy {
    /*
    Thinking analysis of file copying:
    1. Create the input stream of the file and read the file into the program
    2. Create the output stream of the file and write the read file to the file
     */
    public static void main(String[] args) {
        String filePath = "/Users/xinyu/Desktop/111.jpg";
        String targetPath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/wxy.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
            fileOutputStream = new FileOutputStream(targetPath);
            // Define a byte array to improve reading efficiency
            byte[] bytes = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(bytes)) != -1) {
                // Note: offset write is used to prevent cache failure in bytes
                fileOutputStream.write(bytes, 0, readLen); // Read and write
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Buffered copy text file

public static void main(String[] args) {
    String srcPath = "/Users/xinyu/Desktop/test03.txt";
    String targetPath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test03.txt";
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    try {
        bufferedReader = new BufferedReader(new FileReader(srcPath));
        bufferedWriter = new BufferedWriter(new FileWriter(targetPath));
        String data = null;
        // readLine() reads a line, but does not wrap
        while ((data = bufferedReader.readLine()) != null) {
            bufferedWriter.write(data);
            bufferedWriter.newLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Buffered copy binaries

public static void main(String[] args) {
    String srcPath = "/Users/xinyu/Desktop/111.jpg";
    String targetPath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/wxy1.jpg";
    BufferedInputStream bufferedInputStream = null;
    BufferedOutputStream bufferedOutputStream = null;
    try {
        bufferedInputStream = new BufferedInputStream(new FileInputStream(srcPath));
        bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetPath));
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = bufferedInputStream.read(buf)) != -1) {
            bufferedOutputStream.write(buf, 0, readLen);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bufferedInputStream.close();
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

OutputStreamWriter

  1. OutputStreamWriter: subclass of Writer, which can wrap (convert) OutputStream (byte stream) into Writer (character stream)
public static void main(String[] args) throws IOException {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test05.txt";
    FileOutputStream fileOutputStream = new FileOutputStream(filePath);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "gbk");
    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
    bufferedWriter.write("asdasdasdas Ah, actually");
    bufferedWriter.close();
}

Print stream

  1. Print stream has only output stream and no input stream

PrintStream byte stream

public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        // It is standard output by default and is displayed in the console
        out.println("hello world");
        // Because the bottom layer of the print() method is the write() method, you can directly call the write method to print
        out.write("hello world".getBytes());
        // Modify the position of data printed or written
        // 1. Creation method
//        String filePath = "/Users/xinyu/Desktop / self study / Java/JavaTest/test06.txt";
//        PrintStream printStream = new PrintStream(filePath);
//        printStream.write("hello world".getBytes());
        // 2. Setting method
        System.setOut(new PrintStream("/Users/xinyu/Desktop/self-taught/Java/JavaTest/test06.txt"));
        System.out.println("hello, world");


        out.close();
    }

PrintWriter character stream

public static void main(String[] args) throws IOException {
    PrintWriter printWriter = new PrintWriter(System.out);
    // Standard output, displayed in the controller
    printWriter.println("hello, world");
    printWriter.close();

    PrintWriter pt = new PrintWriter(
            new FileWriter("/Users/xinyu/Desktop/self-taught/Java/JavaTest/test06.txt", true));
    pt.println("hello, wxy");
    pt.close();
}

Properties class

Common methods of Properties:

  1. Load: load the key value pair of the configuration file to the Properties object
  2. list: displays the data to the specified device
  3. getProperty(key): get the value according to the key
  4. setProperty(key, value): sets the key value pair to the object Properties
  5. Store: store the key value pairs in Properties in the configuration file. In idea, save the information to the configuration file. If it contains Chinese, it will be stored as Unicode code

Read Properties file

public static void main(String[] args) throws IOException {
    String filePath = "/Users/xinyu/IdeaProjects/IdeaWorkspace/Study_Java/Study_Java_ten/src/mysql.properties";
    // 1. Create Properties object
    Properties properties = new Properties();
    // 2. Load the specified configuration file
    properties.load(new FileReader(filePath));
    // 3. Display key value to console
    properties.list(System.out);
    // 4. Get value according to key
    String user = properties.getProperty("user");
    String pwd = properties.getProperty("pwd");
    System.out.println(user);
    System.out.println(pwd);
}

Modify Properties file

public static void main(String[] args) throws IOException {
    Properties properties = new Properties();
    // establish
    // 1. If the key is not boiled, create it
    // 2. Modify the key if it exists
    /*
    Properties The parent class is HashTable, and the bottom layer is the core method of HashTable
     */
    properties.setProperty("id", "001");
    properties.setProperty("user", "Tom"); // Note: if you save Chinese, the Unicode code will be saved
    properties.setProperty("pwd", "04281023");
    // The first parameter can be the output of character stream or byte stream, and the second parameter is the annotation content
    properties.store(new FileOutputStream("Study_Java_ten/src/mysql2.properties"), null);
}

Homework

Homework01

public static void main(String[] args) throws IOException {
        String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest";
        File file = new File(filePath);
        if (!file.exists()){
            if (file.mkdirs()) {
                System.out.println("The directory does not exist, created successfully");
            }
        } else {
            System.out.println("Creation failed, the directory already exists");
        }
        file = new File(filePath, "test001.txt");
        if (file.createNewFile()) {
            System.out.println("test001 Created successfully");
        } else {
            System.out.println("test001 Creation failed");
        }
        FileWriter fileWriter = new FileWriter(filePath + "/test001.txt");
        fileWriter.write("hello, world");
        fileWriter.close();
    }
}

Homework02

public static void main(String[] args) throws IOException {
    String filePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/test03.txt";
    InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String line = null;
    for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
        System.out.print(i + " ");
        System.out.println(line);
    }
    bufferedReader.close();
}

Homework03

public class Homework03 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filePath = "Study_Java_ten/src/dog.properties";
        String dogFilePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/dog.dat";
        Properties properties = new Properties();
        properties.load(new FileReader(filePath));
        String name = properties.getProperty("name");
        int age = Integer.parseInt(properties.getProperty("age"));
        String master = properties.getProperty("master");

        Dog dog = new Dog(name, age, master);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(dogFilePath));
        objectOutputStream.writeObject(dog);
        objectOutputStream.close();

        readDogDat();
    }

    public static void readDogDat() throws IOException, ClassNotFoundException {
        String dogFilePath = "/Users/xinyu/Desktop/self-taught/Java/JavaTest/dog.dat";
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(dogFilePath));
        Dog dog = (Dog)objectInputStream.readObject();
        System.out.println(dog);
        objectInputStream.close();
    }
}

class Dog implements Serializable {
    private String name;
    private int age;
    private String master;

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

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

Topics: Java Back-end IDEA