Java File Write via ByteBuffer writeFile(File file, byte[] data)

Here you can find the source of writeFile(File file, byte[] data)

Description

write File

License

Apache License

Declaration

public static void writeFile(File file, byte[] data) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    private static final int MAX_BUFFER_SIZE = 4096;

    public static void writeFile(File file, byte[] data) throws IOException {
        FileOutputStream output = null;
        FileChannel fc = null;/* w w  w  .j  a  v a2 s  .  co m*/
        try {
            output = new FileOutputStream(file);
            fc = output.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(MAX_BUFFER_SIZE);
            int offset = 0;
            while (offset < data.length) {
                buffer.clear();
                int len = data.length - offset;
                if (len > MAX_BUFFER_SIZE)
                    len = MAX_BUFFER_SIZE;
                buffer.put(data, offset, len);
                offset += len;
                buffer.flip();
                fc.write(buffer);
            }
        } finally {
            if (fc != null)
                close(fc);
            if (output != null)
                close(output);
        }
    }

    private static void close(InputStream input) {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }

    private static void close(OutputStream output) {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
            }
        }
    }

    private static void close(FileChannel channel) {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
            }
        }
    }
}

Related

  1. writeDelimitedToOutputStream(byte[] bytes, OutputStream outputStream)
  2. writeDouble(BufferedWriter bw, double[] buf)
  3. writeEmpty()
  4. writeFC(String fname, float[] res)
  5. writeFile(File file, byte[] bytes)
  6. writeFile(String source, File outputFile)
  7. writeFileAsByteArray(File file, byte[] par2Data)
  8. writeFileAsStringArray(File file, String[] par2DataArray)
  9. writeFileNIO(String txt, File fyl)