Java ByteBuffer save to file using FileChannel
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Main { public static void main(String[] argv)throws IOException { ByteBuffer b = ByteBuffer.wrap("demo2s.com".getBytes()); toFile(b, new File( "Main.java")); System.out.println("done"); }/* w w w. ja v a 2 s.co m*/ public static void toFile(ByteBuffer buffer, File file) throws IOException { RandomAccessFile raf = null; FileChannel channel = null; try { raf = new RandomAccessFile(file, "rw"); channel = raf.getChannel(); channel.write(buffer); channel.force(false /* metadata */); channel.close(); raf.close(); } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { // Ignored. } } if (raf != null) { try { raf.close(); } catch (IOException e) { // Ignored. } } } } }