The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.nio  [27 examples] > Files  [7 examples]

e171. Writing and Appending a ByteBuffer to a File

If you have one or more ByteBuffers to dump to a file, use a FileChannel.
    // Write bbuf to filename
    ByteBuffer bbuf = getMyData();
    File file = new File("filename");
    
    // Set to true if the bytes should be appended to the file;
    // set to false if the bytes should replace current bytes
    // (if the file exists)
    boolean append = false;
    
    try {
        // Create a writable file channel
        FileChannel wChannel = new FileOutputStream(file, append).getChannel();
    
        // Write the ByteBuffer contents; the bytes between the ByteBuffer's
        // position and the limit is written to the file
        wChannel.write(bbuf);
    
        // Close the file
        wChannel.close();
    } catch (IOException e) {
    }

 Related Examples
e166. Creating a Memory-Mapped File
e167. Persisting Changes to a Memory-Mapped ByteBuffer
e168. Determining If a ByteBuffer Is Direct
e169. Reading from a Channel with a ByteBuffer
e170. Writing to a Channel with a ByteBuffer
e172. Copying One File to Another

See also: Byte Buffers    File Locking    Sockets    Streams   


© 2002 Addison-Wesley.