Java.Streams.What is the difference between IO and NIO?

⚙️ Let’s break down the difference between IO (java.io) and NIO (java.nio) — two major APIs for handling input/output in Java.


✅ TL;DR: Main Differences

FeatureIO (java.io)NIO (java.nio)
TypeStream-oriented (blocking)Buffer-oriented (non-blocking capable)
Blocking?Always blockingCan be non-blocking (with Selectors)
Data AccessSequentialRandom access (via FileChannel)
PerformanceSlower for large dataFaster, especially with large or concurrent I/O
Selectors/Channels❌ Not available✅ Available — great for scalable network I/O
Introduced inEarly Java versionsJava 1.4 (and improved in Java 7 with NIO.2)

🔧 IO (java.io)

  • Based on InputStream and OutputStream
  • Blocking: each read/write call waits until it’s done
  • Easy to use for small/simple file and stream operations

✅ Example:

FileInputStream in = new FileInputStream("file.txt");
int data = in.read(); // blocks until data is read

🚀 NIO (java.nio)

  • Based on Channels and Buffers
  • Uses Selectors for multiplexed, non-blocking I/O
  • Much better for scalable servers, network apps, and performance

✅ Example:

RandomAccessFile file = new RandomAccessFile("file.txt", "r");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer); // fills buffer with data

🔥 NIO.2 (Java 7+)

  • Introduced java.nio.file.* package
  • Added Paths, Files, WatchService (directory monitoring), better file operations

✅ NIO.2 Example:

Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path);

🧠 Summary

Use IO when…Use NIO when…
Simpler, small file I/OHigh-performance or scalable I/O
Blocking behavior is okayYou need non-blocking I/O (e.g., sockets)
You want simplicityYou need power, flexibility, and performance
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.