SoFunction
Updated on 2025-05-07

A comprehensive explanation of Java input stream and output stream

1. Definition and function of input streams and output streams

definition

  • Input Stream: In the Java world, input streams are a mechanism that is responsible for reading data from the external world (data sources such as hard disk file systems, network connections, memory arrays, etc.) into the program.

  • Output Stream: The output stream outputs the data in the program to the external world, which can be a target location such as files and network connections.

effect

Input streams and output streams are the core of Java's implementation of data input and output operations. They build a data interaction bridge between the program and the external environment, allowing the program to read external data for processing and output processing results to the outside.

For example, read the console data into the program. Or output the data in the program to the console

import ;

public class ReadByteByByte {
    public static void main(String[] args) {
        try {
            ("Please enter some content:");
            int input;
            while ((input = ()) != -1) {
                ((char) input);
            }
        } catch (IOException e) {
            ();
        }
    }
}

2. The most basic classes and methods for input streams and output streams

Basic categories

In Java,InputStreamandOutputStreamThey are the most basic abstract classes for input streams and output streams respectively. They use bytes as the basic unit for reading and writing data.

Common methods and usage examples

InputStreamkind

  • int read(): This method reads a byte of data from the input stream, and the return value is the integer corresponding to the byte (range 0 - 255). Returns -1 when the end of the stream is reached.

import ;
import ;
import ;

public class InputStreamExample {
    public static void main(String[] args) {
        try (InputStream is = new FileInputStream("")) {
            int byteData;
            while ((byteData = ()) != -1) {
                ((char) byteData);
            }
        } catch (IOException e) {
            ();
        }
    }
}
  • int read(byte[] b): Try to get the mostRead data of one byte into the byte arrayb, return the actual number of bytes read. If the end of the stream is reached, return -1.

import ;
import ;
import ;

public class InputStreamReadArrayExample {
    public static void main(String[] args) {
        try (InputStream is = new FileInputStream("")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = (buffer)) != -1) {
                for (int i = 0; i < bytesRead; i++) {
                    ((char) buffer[i]);
                }
            }
        } catch (IOException e) {
            ();
        }
    }
}

OutputStreamkind

  • void write(int b): Writes the specified byte to the output stream. Parameters herebAlthough it isintType, but actually only use the lower 8 bits.

    import ;
    import ;
    import ;
    
    public class OutputStreamExample {
        public static void main(String[] args) {
            try (OutputStream os = new FileOutputStream("")) {
                String data = "Hello, World!";
                for (int i = 0; i < (); i++) {
                    ((i));
                }
            } catch (IOException e) {
                ();
            }
        }
    }
  • void write(byte[] b): Translate the byte arraybAll bytes in the output stream are written to the output stream.

import ;
import ;
import ;

public class OutputStreamWriteArrayExample {
    public static void main(String[] args) {
        try (OutputStream os = new FileOutputStream("")) {
            String data = "Hello, Java!";
            byte[] buffer = ();
            (buffer);
        } catch (IOException e) {
            ();
        }
    }
}

3. Can it be read in other units?

AlthoughInputStreamandOutputStreamRead and write in byte-based units, but Java also provides ways to operate in other units:

character

A character stream can be used to read and write in characters. Character streams are built on byte streams and automatically process characters encoding and decoding. For exampleReaderandWriterIt is the abstract base class of character streams.FileReaderandFileWriterIt is a specific implementation class.

import ;
import ;
import ;

public class CharacterStreamExample {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("");
             FileWriter fw = new FileWriter("")) {
            int charData;
            while ((charData = ()) != -1) {
                (charData);
            }
        } catch (IOException e) {
            ();
        }
    }
}

Numbers and Objects

For numbers and objects, data streams and object streams can be used.

  • Data flow:DataInputStreamandDataOutputStreamIt is easy to read and write basic data types (such asintdoublewait).

import ;
import ;
import ;
import ;
import ;

public class DataStreamExample {
    public static void main(String[] args) {
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(""));
             DataInputStream dis = new DataInputStream(new FileInputStream(""))) {
            (123);
            int num = ();
            (num);
        } catch (IOException e) {
            ();
        }
    }
}
  • Object flow:ObjectInputStreamandObjectOutputStreamUsed to read and write Java objects. Objects need to be implementedSerializableOnly interfaces can be serialized and deserialized.

import ;
import ;
import ;
import ;
import ;
import ;

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

    public Person(String name, int age) {
         = name;
         = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class ObjectStreamExample {
    public static void main(String[] args) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(""));
             ObjectInputStream ois = new ObjectInputStream(new FileInputStream(""))) {
            Person person = new Person("John", 30);
            (person);
            Person readPerson = (Person) ();
            ("Name: " + () + ", Age: " + ());
        } catch (IOException | ClassNotFoundException e) {
            ();
        }
    }
}

4. The relationship between character streams, object streams, etc. and byte streams

Character streams, object streams, data streams, etc. are closely related to byte streams, and they are built on the basis of byte streams.

  • Character stream: A character encoding protocol is added to the basis of byte stream. When reading data, a specified number of bytes is read according to the encoding protocol, and then decodes the corresponding characters; when writing data, the characters are encoded into bytes and output through a byte stream.

  • Object stream: When input, first obtain the serialization result of the object (byte stream), then use the byte stream to read, and then deserialize to obtain the object; when output, serialize the object to obtain the byte stream, and then use the byte stream to transmit the byte stream.

  • Data stream: On the basis of byte stream, it provides the function of reading and writing basic data types, which converts basic data types into bytes for reading and writing.

To sum up, byte streams are the basis of Java input and output stream system. Other types of streams are extended based on byte streams to meet different data processing needs.

5. The principle of Buffered input stream to achieve faster read efficiency

I see that FIleInputStream always calls the local method read0 every time I read the data. If I encounter large files frequently call it, it may cause the efficiency to be relatively low. Is there any better way?

In Java, likeBufferedInputStreamandBufferedReaderThis type of input stream with buffers can improve read efficiency, and its core principle is to reduce the number of system calls. The following is a specific explanation:

  • System call overhead

System calls are the process by which a program requests services from an operating system kernel, such as reading data from a disk, network, or console. Each system call requires context switching, that is, switching from user mode to kernel mode, which consumes a lot of time and resources. If only a small amount of data is read at a time, system calls will be made frequently, resulting in inefficiency.

  • The role of buffer

The input stream with a buffer internally maintains a buffer (usually a byte array or character array). When the program calls the read method for the first time, it makes a system call, reading a large piece of data from a data source (such as a file, a network, etc.) into the buffer. After that, when the program performs a read operation, it will first obtain data from the buffer instead of making a system call directly. Only when the data in the buffer is read, the system call will be made again to read the new data to the buffer.

For example,BufferedInputStreamThe stream will be input from the underlying layer at one time (such asFileInputStream) reads multiple bytes into the byte array buffer inside it, and subsequent read operations can directly obtain data from this buffer, reducing the number of interactions with the underlying input source, thereby improving read efficiency.

How to use the Buffered input stream

1. Use of BufferedInputStream (processing byte streams)

BufferedInputStreamFor processing byte streams, here is a simple example showing how to useBufferedInputStreamRead the file:

import ;
import ;
import ;
import ;

public class BufferedInputStreamExample {
    public static void main(String[] args) {
        try (InputStream fis = new FileInputStream("");
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            int byteData;
            while ((byteData = ()) != -1) {
                ((char) byteData);
            }
        } catch (IOException e) {
            ();
        }
    }
}

In the above code, first create aFileInputStreamUsed to read byte data from a file and then pass it as a parameter toBufferedInputStreamThe constructor of  creates an input stream with a buffer. Afterwards, throughBufferedInputStreamofread()The method reads data, it will first obtain data from the buffer, and then performs a system call to read new data when the buffer is empty.

2. Use of BufferedReader (processing character streams)

BufferedReaderUsed to process character streams, the following is one to useBufferedReaderExample of reading files:

import ;
import ;
import ;

public class BufferedReaderExample {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader(""))) {
            String line;
            while ((line = ()) != null) {
                (line);
            }
        } catch (IOException e) {
            ();
        }
    }
}

In this example, aFileReaderUsed to read character data from a file and then pass it toBufferedReaderconstructor.BufferedReaderThe character data will be read to its internal buffer, and the character data will be read to its internal buffer, throughreadLine()The method can easily read data by line, improving the efficiency of reading text files.

By using input streams with buffers, the number of system calls can be significantly reduced, thereby improving the efficiency of data reading.

Summarize

This is the end of this article about Java input streams and output streams. For more related Java input streams and output streams, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!