Java: what exactly is the difference between NIO and NIO.2?

前端 未结 3 709
礼貌的吻别
礼貌的吻别 2021-01-30 00:55

I don\'t quite understand how different they are from each other so I have some inquiries regarding these two packages.

After looking around a bit on Google, it seems li

3条回答
  •  青春惊慌失措
    2021-01-30 01:15

    My take:

    Short version

    It’s the addition of java.nio.file package with its high level much enhanced file and file system functionality.
    From the perspective of network sockets or low level file access, NIO == NIO.2 with a few convenience improvements.

    Longer version

    Java IO

    Package: java.io
    Old blocking I/O API

    Java NIO

    Added in Java 1.4, the new non-blocking API.
    Package: java.nio
    Java non-blocking IO. Classes like Selector, SelectorKey, Channel.
    It seems to me the NIO was a big step up for network I/O (Selector, SelectorKey, SocketChannel, ServerSocketChannel, Buffer), much less for file I/O (FileChannel and Buffer only, including memory mapped files). This is a fairly low level API, for both network and file parts.

    Java NIO.2

    Added in Java 7. It’s mainly about addition of much improved file and filesystem manipulation and addressing API. The new file and filesystem related API is relatively high level.

    Package: java.nio.file and few additions to parent java.nio.
    This additions are for file I/O and only few minor additions to network I/O or low level file API.

    Most notable low-level, not necessary file related, API additions are AsynchronousSocketChannel, AsynchronousServerSocketChannel and AsynchronousFileChannel, which adds callbacks variants to some methods. The Asynchronous versions of are mainly a convenience addition; such mapping interfaces could have been hacked together even before, but now they are available out-of-the box in the JRE.

    The new file API brings a lots of goodies - much more useful file system addressing with Path, much improved ZIP file manipulation using custom file system provider, special file attributes access, lots of convenience methods like reading whole file with one command, copying file with one command etc. But it's all file/filesystem related and all quite high level.

    Reiterating what I have already said above, from the perspective of network sockets or low level file access, NIO == NIO.2

    Relevant links

    • Java NIO - non-blocking channels vs AsynchronousChannels misleadingly named questions; both synchronous and asynchronous variants of Channel and Socket are indeed non-blocking.
    • https://docs.oracle.com/javase/7/docs/technotes/guides/io/enhancements.html#jdk7 – mentions only the file related changes under NIO.2 section.

提交回复
热议问题