- Forward


Channels in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Overview
Back SMYC Forward
  • Purpose:
    • Provide access to native I/O services of an operating system while still maintaining platform independence
  • Conceuptualization:
    • A channel is a conduit/gateway that uses a buffer to send and receive data
Approach
Back SMYC Forward
  • Implementations:
    • Vary considerably from one operating system to another
  • Interfaces:
    • Provide a uniform (i.e., OS-independent) view of the implementations
Some Channels
Back SMYC Forward
channels
Capabilities
Back SMYC Forward
  • Channel :
    • isOpen()
    • close()
  • ReadableByteChannel :
    • read()
  • WriteableByteChannel :
    • write()
  • ByteChannel :
    • Extends ReadableByteChannel and WriteableByteChannel
File I/O Using Channels
Back SMYC Forward
  • The Channel:
    • FileChannel
  • Obtaining a Channel:
    • Using the static open() method in the FileChannel class
    • Using the static newByteChannel() method in the Files class
File I/O Using Channels (cont.)
Back SMYC Forward

An Example of Input

javaexamples/nio/ShowWithChannel.java
 
File I/O Using Channels (cont.)
Back SMYC Forward

An Example of Output

javaexamples/nio/AppendToHistory.java
 
File I/O Using Channels (cont.)
Back SMYC Forward
  • Convenience Methods for Input:
    • Files.readAllBytes(Path) returns a byte[]
    • Files.readAllLines(Path) returns a List<String>
  • Convenience Methods for Output:
    • Files.write(Path, byte[])
File I/O Using Channels (cont.)
Back SMYC Forward

An Example using Convenience Methods

javaexamples/nio/ShowWithConvenienceMethods.java
 
File Locking
Back SMYC Forward
  • Purpose:
    • Controlling access at the process level
  • Some Limitations:
    • Specific features are OS-specific
    • Locks are applied per file (not per channel)
Scatter/Gather
Back SMYC Forward
  • Purpose:
    • Perform a single I/O operation on multiple buffers
  • When Writing:
    • Drain data from multiple buffers and send it along on channel
  • When Reading:
    • Fill multiple buffers in sequence (until each reaches its limit) from a single channel
Scatter/Gather (cont.)
Back SMYC Forward
  • ScatteringByteChannel :
    • Has a read() method that is passed a ByteBuffer[]
  • GatheringByteChannel :
    • Has a write() method that is passed a ByteBuffer[]
Other Important Channels
Back SMYC Forward
  • DatagramChannel :
    • A channel for datagram-oriented sockets
  • SocketChannel :
    • A channel for stream-oriented sockets
There's Always More to Learn
Back -