1. Java IO (Blocking IO)
Basic concepts
- Java IO is an API provided by the Java platform for input and output operations.
- Java IO basedStreamThe model of data flows from one place to another like water flow.
- Java IO is mainlyBlocking I/O (Blocking I/O), that is, the thread will be blocked when performing I/O operations until the operation is completed.
- Traditional IO refers to
Some components under the package (File, InputStream, OutputStream, Reader, Writer).
Classification of IO streams
By data transmission direction:
-
Input Stream:Used to read data from a data source (for example, from a file, a network connection, a keyboard, etc.). by
InputStream
orReader
As a base class. -
Output Stream:Used to write data to the target (for example, to a file, network connection, console, etc.). by
OutputStream
orWriter
As a base class.
By data transmission unit:
-
Byte Stream:Data transfer in bytes (8 bits). by
InputStream
andOutputStream
As a base class. Suitable for processing binary data (e.g., pictures, audio, video, etc.). -
Character Stream:Data transfer in characters (16 bits). by
Reader
andWriter
As a base class. Suitable for processing text data.
Core classes and interfaces
InputStream
(Byte input stream):
-
FileInputStream
: Read bytes from the file. -
ByteArrayInputStream
: Read bytes from the byte array. -
ObjectInputStream
: Read an object from the object stream. -
BufferedInputStream
: Buffered byte input stream to improve read efficiency.
OutputStream
(Byte output stream):
-
FileOutputStream
: Write bytes to the file. -
ByteArrayOutputStream
: Write bytes into the byte array. -
ObjectOutputStream
: Writes an object to the object stream. -
BufferedOutputStream
: Buffered byte output stream to improve write efficiency.
Reader
(Character input stream):
-
FileReader
: Read characters from the file. -
CharArrayReader
: Read characters from character array. -
BufferedReader
: Buffered character input stream to improve read efficiency. -
InputStreamReader
: Converts the byte input stream to a character input stream (requires specified character encoding).
Writer
(Character output stream):
-
FileWriter
: Write characters to the file. -
CharArrayWriter
: Write characters into the character array. -
BufferedWriter
: Buffered character output stream to improve write efficiency. -
OutputStreamWriter
: Converts the byte output stream to a character output stream (requires specified character encoding). -
File
:An abstract representation of a file or directory.
IO operation process (taking reading files as an example)
-
create
File
Object:Specifies the file path to read. -
create
FileInputStream
Object:WillFile
The object is passed as a parameter toFileInputStream
The constructor method of creating aFileInputStream
Object. -
create
BufferedInputStream
Object (optional):WillFileInputStream
The object is passed as a parameter toBufferedInputStream
The constructor method of creating aBufferedInputStream
Object, improve reading efficiency. -
Read data:use
read()
Methods read data from the input stream. -
Close the stream:After completing the read operation, be sure to close the input stream and free up the resource (close it first).
BufferedInputStream
, close againFileInputStream
)。
Code example (read file content):
import ; import ; import ; import ; public class IOExample { public static void main(String[] args) { File file = new File(""); // Replace with your file path try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) { // Use the try-with-resources statement to automatically close the stream byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = (buffer)) != -1) { // Process the read data String data = new String(buffer, 0, bytesRead); (data); } } catch (IOException e) { (); } } }
2. Java NIO (Non-blocking IO)
Basic concepts
- Java NIO is a new set of I/O APIs introduced in Java 1.4 to provide high-performance, non-blocking I/O operations.
- NIO UseChannelandBuffermodel, not flow.
- NIO is mainlyNon-blocking I/O (Non-blocking I/O), that is, the thread will not be blocked when performing I/O operations, but can perform other tasks.
- NIO UseSelectorTo listen to events in multiple channels, implement single thread management of multiple connections.
Core Components
Channel:
- Channels are similar to streams, but can perform bidirectional data transmission (can be read or written).
- Common channels:
-
FileChannel
: Used for file I/O. -
SocketChannel
: Used for TCP network I/O (client). -
ServerSocketChannel
: Used for TCP network I/O (server side). -
DatagramChannel
: Used for UDP network I/O.
-
Buffer:
- A buffer is a container used to store data, essentially a byte array (ByteBuffer) or a character array (CharBuffer).
- NIO uses buffers for data transfer, rather than reading data directly from or writing data to the channel.
- Common buffers:
-
ByteBuffer
: Byte buffer. -
CharBuffer
: Character buffer. -
ShortBuffer
: Short integer buffer. -
IntBuffer
: Integer buffer. -
LongBuffer
: Long integer buffer. -
FloatBuffer
: Floating point buffer. -
DoubleBuffer
: Double precision floating point buffer.
-
Selector:
- The selector allows a single thread to listen for events on multiple channels (such as connection establishment, data readable, data writable, etc.).
- Using selectors can avoid creating one thread for each connection, thereby improving concurrency performance.
NIO operation process (taking the reading of SocketChannel data as an example)
-
create
ServerSocketChannel
:Listen to client connections. -
create
SocketChannel
:Accept client connections. -
Will
SocketChannel
Register toSelector
:Specify the event to listen for (e.g.OP_READ
,OP_WRITE
,OP_CONNECT
,OP_ACCEPT
)。 -
create
ByteBuffer
:Used to store read data. -
Call
()
method:Blocks the channel waiting for an event to occur. -
Get ready channels:
()
Returns a collection of all ready channels. - Handling events:Iterate through the set of ready channels and perform corresponding operations according to different event types (such as reading data, writing data).
-
Read data:Call
(buffer)
Read data from the channel to the buffer. - Processing buffer data:Read data from the buffer and process it.
- Close the channel and selector:After completing the operation, be sure to close the channel and selector to free up resources.
Code example (read data using SocketChannel):
import ; import ; import ; import ; public class NIOExample { public static void main(String[] args) throws IOException { // 1. Create SocketChannel SocketChannel socketChannel = (); (new InetSocketAddress("", 80)); (false); // Set to non-blocking mode // 2. Create ByteBuffer ByteBuffer buffer = (1024); // 3. Read data from Channel to Buffer int bytesRead = (buffer); while (bytesRead > 0) { // Switch to read mode (); // 4. Read data from the Buffer while (()) { ((char) ()); } // Clear the Buffer and prepare for the next read (); bytesRead = (buffer); } (); } }
3. The difference between Java IO and NIO
characteristic | Java IO (Blocking IO) | Java NIO (Non-blocking IO) |
---|---|---|
Data transmission method | Stream-based | Channels and buffers |
I/O model | Blocking I/O (Blocking I/O) | Non-blocking I/O (Non-blocking I/O) |
Selector | No | Yes (Selector) |
API | Simple and easy to use | Relatively complex, you need to understand concepts such as channels, buffers, and selectors. |
performance | Low performance (with high concurrency) | High performance (with high concurrency) |
Threading model | Usually using a multi-threaded model (one thread per connection) | Typically using a single thread multiplexing model (one thread manages multiple connections) |
Applicable scenarios | Applications with low concurrency, fewer connections, or blocking scenarios | Applications with high concurrency and high connections require high performance and non-blocking scenarios, such as network servers, chat servers, etc. |
4. Which I/O mode should I choose?
- If your application is low concurrency, fewer connections, and can accept blocking, Java IO is still a good choice because it is simple and easy to use.
- If your application is high concurrency, has a large number of connections, and has high performance requirements, you should use Java NIO.
- Generally speaking, it is recommended to use the NIO model directly for better performance.
Summarize
Java IO and NIO are both APIs provided by the Java platform for input and output operations.
Java IO is a stream-based model that is simple to use but has low performance; Java NIO is a channel and buffer-based model that provides high-performance, non-blocking I/O operations.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.