NIO channels do not exist without IO streams?

Viewed 87

In H. Shildt's book I read:

Channels do not exist without context. The context for these is a series of I/O stream classes from java.io.

I've also seen this statement when learning NIO, but very few times.

Anyway, the following code works without creating I/O stream. Why? And what variant is right - with or without IO streams?

try (FileChannel channel = (FileChannel) 
    Files.newByteChannel(Paths.get("test.txt")) ) {
    
    // some code

} catch(...)
2 Answers

Channels class defines static methods that support the interoperation of the stream classes of the java.io package with the channel classes of java.nio package.

Other than the interoperability reasons, it's not a requirement as such if using java.nio apis directly, jdk 7 or later in specific.

More here: https://docs.oracle.com/javase/7/docs/api/java/nio/channels/Channels.html

So the quote here is possibly with reference to the Java util class Channels, not w.r.t to java.nio in general.

I don't think this quote implies that there is a specific technical requirement for one to exist without the other.

In my opintion "context" in this case means "circumstances that are useful to know when trying to understand this topic".

In other words: the I/O stream classes where the original way to do I/O in Java. NIO is an evolution on top of it. NIO doesn't necessarily require the basic stream classes, but understanding these original concepts will help with understanding NIO.

Related