Writes the remaining bytes of a byte buffer to the given file. - Java java.nio

Java examples for java.nio:ByteBuffer File

Description

Writes the remaining bytes of a byte buffer to the given file.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.*;

public class Main {
    /**//from   w w  w.  ja  v  a 2  s  .com
     * Writes the remaining bytes of a byte buffer to the given file. 
     * If the file already exists, it will be overwritten and its size will be 
     * truncated to the amount of remaining bytes in the given buffer.
     * 
     * @param path
     * @param bb
     * @throws IOException 
     */
    public static void save(Path path, ByteBuffer bb) throws IOException {
        try (FileChannel fc = FileChannel.open(path, WRITE, CREATE)) {
            fc.truncate(bb.remaining());
            fc.write(bb);
        }
    }
}

Related Tutorials