Java Byte Array Save to File nio writeToBinaryFile(String filename, byte[] data)

Here you can find the source of writeToBinaryFile(String filename, byte[] data)

Description

Writes the binary data to the specified file.

License

Open Source License

Parameter

Parameter Description
filename the file to write to
data the data to write

Return

true if writing was successful

Declaration

public static boolean writeToBinaryFile(String filename, byte[] data) 

Method Source Code

//package com.java2s;
/*//from   w w w. jav  a 2 s.  c o m
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

import java.nio.file.Files;

import java.nio.file.StandardOpenOption;

public class Main {
    /**
     * Writes the binary data to the specified file. The file is always overwritten.
     *
     * @param filename   the file to write to
     * @param data   the data to write
     * @return      true if writing was successful
     */
    public static boolean writeToBinaryFile(String filename, byte[] data) {
        return writeToBinaryFile(filename, data, false);
    }

    /**
     * Writes the binary data to the specified file.
     *
     * @param filename   the file to write to
     * @param data   the data to write
     * @param append   whether to append the file
     * @return      true if writing was successful
     */
    public static boolean writeToBinaryFile(String filename, byte[] data, boolean append) {
        StandardOpenOption[] options;

        try {
            if (append)
                options = new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND,
                        StandardOpenOption.WRITE };
            else
                options = new StandardOpenOption[] { StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE };
            Files.write(new File(filename).toPath(), data, options);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

Related

  1. fileWriteBytes(byte[] data, String file)
  2. writeBytes(final byte[] bytes, final OutputStream output)
  3. writeHeader(File input, ByteArrayOutputStream headerStream)
  4. writeIntChars(int value, int index, byte[] buf)
  5. writeToFile(File file, byte[] content)