Java FileChannel write remaining ByteBuffer

Description

Java FileChannel write remaining ByteBuffer



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 {
    /**//  w ww  .ja  v a2s .c  o m
     * 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);
        }
    }
}



PreviousNext

Related