Search code examples
javaionio

Which File reading Writing IO class to use and when?


As we all know with Java comes the very complicated list of IO classes plus there is another thing called NIO.

  1. I was wondering if there is any thumb rule that could explain the situations and best IO to use for the problem( considering Web application in mind ).

  2. I always get confused which one to use when, another query is How should I remember the implementation of all these classes. It get confusing all the time


Solution

  • Difference between IO vs NIO:

    +-------------------------------------------------------+-------------------------------------------------------------------+
    |                          IO                           |                            NIO(New IO)                            |
    +-------------------------------------------------------+-------------------------------------------------------------------+
    | Stream oriented                                       | Channels/Buffers oriented                                         |
    | Thread Blocking IO(Synchronous)                       | Non Thread blocking IO(Asynchronous i.e notification based)       |
    | Read or Write can do one byte/char at a time.         | Channel is bidirectional.                                         |
    | Readers are for read only, Writers are for write only | Channel can read and write byte buffer(not char buffer).          |
    | Buffer creates in JVM heap memory.                    | Buffer can be outside or in-memory of JVM.                        |
    | Charset is limited ot UTF-8.                          | Charset support expanded to UTF-16 and more.                      |
    |                                                       | "Selectors" allows a single thread to handle multiple Channel's.) |
    +-------------------------------------------------------+-------------------------------------------------------------------+
    
    • java.io package was introduced in JDK 1.0 (January 23, 1996)
    • java.nio (NIO stands for non-blocking I/O) API was introduced with the J2SE 1.4 (February 6, 2002)
    • An extension to NIO that offers a new file system API, called NIO.2, was released with Java SE 7 (July 28, 2011), it includes new sub-package java.nio.file under java.nio

    • Blocking call: Control returns only when the call completes

    • Non blocking call(often refers to polling): Control returns immediately.

    Enhancements in Java I/O