// @topic T11935 FileChannel, StandardOpenOption, and ByteBuffer
// @brief Writing raw integer into a file with FileChannel

package bcc.week14_file_io;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;

public class MainApp {

    public static void main(String[] args) {
        Path binFilePath = Paths.get( "demo.bin" );
        try {
            FileChannel fc = 
                    (FileChannel)Files.newByteChannel( binFilePath, CREATE, WRITE );
            int value = 123; // value to save in the file
            int capacity = 4; // space to accommodate one integer
            ByteBuffer bb = ByteBuffer.allocate( capacity ); 
            bb.putInt( value );
            
            // "rewind" buffer position to have the values written.
            // Otherwise nothing is written into the file.
            bb.rewind();
            
            fc.write( bb );
            fc.close();
                
        } catch ( IOException ex ) {
            System.out.println( ex );
        }

    }//main

}//class MainApp