<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.nio.file.*;



/**
 * An application that uses a SeekableByteChannel to read some files
 * and display them on the console.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ShowWithChannel
{
    /**
     * The entry point of the application.
     *
     * @param args  The command line arguments (containing the file names)
     */
    public static void main(String[] args)
    {
        for (int i=0; i&lt;args.length; i++)
        {
            Path path = Paths.get(args[i]);
            
            // Use a try-with-resources statement to ensure that the Channel
            // is closed regardless of what exceptions are thrown
            try (SeekableByteChannel channel = Files.newByteChannel(path))
            {
                String  encoding = System.getProperty("file.encoding");
                Charset charset  = Charset.forName(encoding);                

                // Create a ByteBuffer (with capacity 10)
                ByteBuffer buffer = ByteBuffer.allocate(10);
                
                // Iteratively attempt to read bytes into the buffer 
                // (which changes position)
                while (channel.read(buffer) &gt; 0)
                {
                    // Reset the position to 0 and discard the mark 
                    // (so that it can be decoded)
                    buffer.rewind(); 

                    // Convert the ByteBuffer to a CharBuffer 
                    // (which changes position to limit)
                    CharBuffer chars = charset.decode(buffer);
                    
                    // Print the CharBuffer
                    System.out.print(chars);

                    // Set limit to position and position to 0
                    // (so that the buffer can be used for input again)
                    buffer.flip();
                }
            }
            catch (IOException ioe)
            {
                System.out.printf("Couldn't read %s\n", args[i]);
            }
        }
    }
}
</pre></body></html>