Java IO Stream概述

一、What are the Streams

Java IO Stream概述
In computer science Streams are defined as the ordered sequence of data elements.

  • Provides a common I/O model
  • Abstract details of underlying source or destination
  • Stream types are unidirectional(单向)

Java IO Stream概述
We can divide the streams into two categories:

  • Byte streams – Interacts as binary data
  • Text streams – Interacts as Unicode characters

二、Input/Output Stream

the data flows from a source known as a data source to a destination known as a data sink.
The data is read from a data source to a Java program. A Java program writes data to a data sink. The stream that connects a data source and a Java program is called an input stream. The stream that connects a Java program and a data sink is called an output stream.
Java IO Stream概述
Java IO Stream概述

三、How we work with input/output stream

To read data from a data source into a Java program, you need to perform the following steps:

  • Identify the data source. It may be a file, a string, an array, a network connection, etc.
  • Construct an input stream using the data source that you have identified.
  • Read the data from the input stream. Typically, you read the data in a loop until you have read all the data from the input stream. The methods of an input stream return a special value to indicate the end of the input stream.
  • Close the input stream. Note that constructing an input stream itself opens it for reading. There is no explicit step to open an input stream. However, you must close the input stream when you are done reading data from it.

To write data from a data sink from a Java program, you need to perform the following steps:

  • Identify the data sink. That is, identify the destination where data will be written. It may be a file, a string, an array, a network connection, etc.
  • Construct an output stream using the data sink that you have identified.
  • Write the data to the output stream.
  • Close the output stream. Note that constructing an output stream itself opens it for writing.There is no explicit step to open an output stream. However, you must close the output stream when you are done writing data to it.

1.Reader(read方法)、Writer(write、flush源码解析)、BufferedWriter源码解析
2. InputStream(read方法)、OutputStream(write方法)、BufferedOutputStream源码解析

参考:
https://laptrinhx.com/nio-new-input-output-vs-io-input-output-and-nio-2-in-java-3345086392/
https://www.zoltanraffai.com/blog/streams-in-java-8/