[Learning JAVA from scratch | Thirty-four articles] IO flow

Table of contents

Foreword:

IO flow introduction:

Common methods for IO streams:

1. Byte stream class:

2. Character stream class:

Summarize:


Foreword:

                IO flow is the solution for storing and reading data, and it is a chapter with many knowledge points, so our introduction to IO flow will be divided into multiple articles for detailed explanation, and mastering IO flow can greatly improve our efficiency , to simplify our code execution efficiency.

IO flow introduction:

As we know above, if we want to implement the archiving function of the program, we need to implement two functions in total:

1. Save the data in the file, which is the role of the File class in our last article

2. Realize the function of reading file data by the program, which is the function of the IO stream we will introduce in the next few articles

In Java, IO Stream (Input/Output Stream) is a mechanism for processing input and output. It provides a way to read and write data, allowing programs to interact with files, networks, and more. The IO stream in Java is divided into two types: byte stream and character stream.

Byte stream operations perform input and output in units of bytes . The byte stream is mainly composed of two abstract classes InputStream and OutputStream and their various implementation classes. Common byte stream classes include FileInputStream, FileOutputStream, ByteArrayInputStream, ByteArrayOutputStream, etc.

The character stream operation performs input and output in units of characters , and it can directly operate Unicode characters. The character stream is mainly composed of two abstract classes, Reader and Writer, and their various implementation classes. Common character stream classes include FileReader, FileWriter, BufferedReader, BufferedWriter, etc.

 Byte streams can operate on all types of files, and character streams can only operate on plain text files.

Common methods for IO streams:

1. Byte stream class:

1.FileOutputStream

FileOutputStream is a byte output stream used in the Java IO library to write data to a file. It inherits from the OutputStream class and adds some methods specific to file output. With FileOutputStream, we can write byte data to a local file, which can be a single byte, an array of bytes, or a portion of an array of bytes.

The basic steps to use FileOutputStream are as follows:

  1. Create a FileOutputStream object : by calling the constructor of FileOutputStream, specify the file path and file name to be written. For example:FileOutputStream fos = new FileOutputStream("file.txt");

  2. Write data : Use the write() method provided by FileOutputStream to write data to a file. There are several overloaded write() methods available. Common methods include:

    • void write(int b): Write the specified bytes to the file.
    • void write(byte[] b): Writes all data in the specified byte array to the file.
    • void write(byte[] b, int off, int len): Write part of the data in the specified byte array to the file, the parameter off indicates the starting position of the array, and the parameter len indicates the number of bytes to be written.

    For example, use the write(byte[]) method to write string data to a file:

    String data = "Hello, World!";
    byte[] bytes = data.getBytes();
    fos.write(bytes);
    
  3. Flush data : If you need to write data to disk immediately instead of waiting for the buffer to be full or closing the stream, you can call the flush() method. For example:fos.flush();

  4. Close the stream : Be sure to close the FileOutputStream when you are done using it to release resources. It can be closed using the close() method. For example:fos.close();

The complete sample code is as follows:

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

public class FileOutputStreamExample {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("file.txt");
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            fos.write(bytes);
            fos.flush();
            fos.close();
            System.out.println("Data has been written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileOutputStream also provides some other methods, such as getFD() to obtain the file descriptor associated with the stream, and the seek() method to write data at a specific position.

It should be noted that exceptions such as IOException or FileNotFoundException may be thrown when using FileOutputStream, so proper exception handling should be performed when using it.

2.FileInputStream

FileInputStream is a byte input stream used in the Java IO library to read data from a file. It inherits from the InputStream class and provides some methods specific to file input. Through FileInputStream, we can read byte data from the file, which can be a single byte or a group of bytes.

The basic steps to use FileInputStream are as follows:

  1. Create a FileInputStream object : by calling the constructor of FileInputStream, specify the file path and file name to be read. For example:FileInputStream fis = new FileInputStream("file.txt");

  2. Read data : Use the read() method provided by FileInputStream to read data. There are several overloaded read() methods that can be used. Common methods include:

    • int read(): Reads a byte of data and returns an integer representation (0-255) of that byte of data, or -1 when the end of the file is reached.
    • int read(byte[] b): Read a certain number of bytes from the file and store it in the specified byte array b, and return the actual number of bytes read. Returns -1 when reading to the end of the file.
    • int read(byte[] b, int off, int len): Read up to len bytes from the file into the specified byte array b, starting from the offset off of the array, and return the actual number of bytes read. Returns -1 when reading to the end of the file.

    For example, use the read(byte[]) method to read data from a file and print it to the console:

    FileInputStream fis = new FileInputStream("file.txt");
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
        System.out.write(buffer, 0, bytesRead);
    }
    
  3. Close the stream : Be sure to close the FileInputStream when you are done using it to release resources. It can be closed using the close() method. For example:fis.close();

The complete sample code is as follows:

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

public class FileInputStreamExample {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("file.txt");
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                System.out.write(buffer, 0, bytesRead);
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileInputStream also provides some other methods, such as available() returns the number of bytes left to be read, skip(long n) is used to skip the specified number of bytes, etc.

It should be noted that exceptions such as IOException or FileNotFoundException may be thrown when using FileInputStream, so appropriate exception handling should be performed when using it.

2. Character stream class:

The character stream can be used to solve the code reading problem, because the encoding of Chinese characters is not a byte size, and if we output according to the byte stream when reading the code, the Chinese character encoding will be converted into garbled characters by mistake, so we design The character stream is defined, so that when reading the code, it is not read according to the byte, but the character.

In Java, the character stream class is a collection of classes for reading and writing character data. They are all located in the java.io package. Commonly used character stream classes include:

  1. FileReader and FileWriter : Character stream classes for reading and writing character files.

    • FileReader: Used to read character files (such as text files). It reads the contents of the file in units of characters.
    • FileWriter: Used to write character files (such as text files). It writes data to a file in units of characters.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamsExample {
    public static void main(String[] args) {
        try {
            // 创建FileReader对象并指定要读取的文件路径
            FileReader reader = new FileReader("input.txt");

            // 创建FileWriter对象并指定要写入的文件路径
            FileWriter writer = new FileWriter("output.txt");

            int character;
            // 逐字符读取文件内容并写入到输出文件中
            while ((character = reader.read()) != -1) {
                writer.write(character);
            }

            // 关闭流
            reader.close();
            writer.close();

            System.out.println("文件复制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. BufferedReader and BufferedWriter : provide a buffer function to speed up character input and output operations.

    • BufferedReader: used to read character data, and provides a buffer function, which can improve reading efficiency.
    • BufferedWriter: Used to write character data, and provides a buffer function, which can improve writing efficiency.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedCharacterStreamsExample {
    public static void main(String[] args) {
        try {
            // 创建BufferedReader对象并指定要读取的文件路径
            BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

            // 创建BufferedWriter对象并指定要写入的文件路径
            BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

            String line;
            // 逐行读取文件内容并写入到输出文件中
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine(); // 写入换行符
            }

            // 关闭流
            reader.close();
            writer.close();

            System.out.println("文件复制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. InputStreamReader and OutputStreamWriter: used to handle the conversion between byte stream and character stream.

    • InputStreamReader: Converts a byte stream to a character stream. It can specify a character set to decode bytes into characters.
    • OutputStreamWriter: Converts a character stream to a byte stream. It can specify a character set, which encodes characters into bytes.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class EncodingExample {
    public static void main(String[] args) {
        try {
            // 使用InputStreamReader将字节流转换为字符流
            FileInputStream fis = new FileInputStream("input.txt");
            InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
            int data;
            while ((data = reader.read()) != -1) {
                System.out.print((char) data);
            }
            reader.close();

            // 使用OutputStreamWriter将字符流转换为字节流
            FileOutputStream fos = new FileOutputStream("output.txt");
            OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
            writer.write("你好,世界!");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Summarize:

        In this article, we introduced two types of IO streams: byte stream and character stream. In actual code writing, we also need to determine which one is more suitable according to the actual situation.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

Guess you like

Origin blog.csdn.net/fckbb/article/details/132015535