The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.nio  [27 examples] > Streams  [2 examples]

e183. Creating a Stream from a Channel

This example uses methods from Channels.newOutputStream() and Channels.newInputStream() to create streams on a file channel. Note: If the example had created a direct ByteBuffer from the file channel (see e166 Creating a Memory-Mapped File), any reads or writes to the streams would appear in the direct ByteBuffer.
    try {
        // Create a read/writeable file channel
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    
        // Create an output stream on the channel
        OutputStream os = Channels.newOutputStream(channel);
    
        // Create an inputstream on the channel
        InputStream is = Channels.newInputStream(channel);
    
        // Close the channel
        is.close();
    } catch (IOException e) {
    }

 Related Examples
e184. Creating a Stream on a ByteBuffer

See also: Byte Buffers    File Locking    Files    Sockets   


© 2002 Addison-Wesley.