Java FileOutputStream Write Byte Array writeBytes(File f, byte[] data)

Here you can find the source of writeBytes(File f, byte[] data)

Description

write Bytes

License

Apache License

Declaration

public static void writeBytes(File f, byte[] data) throws IOException 

Method Source Code


//package com.java2s;
/*/*  ww w .  j ava 2  s.c o m*/
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void writeBytes(File f, byte[] data) throws IOException {
        byte[] buf = new byte[1024];

        BufferedOutputStream bos = null;
        ByteArrayInputStream bais = null;

        try {
            bos = new BufferedOutputStream(new FileOutputStream(f));
            bais = new ByteArrayInputStream(data);
            int len;
            while ((len = bais.read(buf)) > 0) {
                bos.write(buf, 0, len);
            }
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bais != null) {
                bais.close();
            }
        }
    }

    public static void write(File f, byte[] data) throws IOException {
        if (f.exists()) {
            // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds
            // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                throw new RuntimeException("Unable to sleep");
            }
        }

        // Attempt to write the file
        writeBytes(f, data);

        // Now check the file was written and re-attempt if it was not
        // Need to do this for testing, to ensure the texts are read the same way, otherwise sometimes you get tail \n sometimes you don't
        int count = 0;
        while (!areByteArraysEqual(data, readBytes(f)) && count < 5) {
            // The file failed to write, try 5 times, calling GC and sleep between each iteration
            // Sometimes windows takes a while to release a lock on a file
            System.gc();
            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {
                throw new RuntimeException("This should never happen");
            }
            writeBytes(f, data);
            count++;
        }

        //areByteArraysEqual

        if (count == 5) {
            throw new IOException("Unable to write to file:" + f.getCanonicalPath());
        }
    }

    public static boolean areByteArraysEqual(byte[] b1, byte[] b2) {

        if (b1.length != b2.length) {
            return false;
        }

        for (int i = 0, length = b1.length; i < length; i++) {
            if (b1[i] != b2[i]) {
                return false;
            }
        }

        return true;
    }

    public static byte[] readBytes(File f) throws IOException {
        byte[] buf = new byte[1024];

        BufferedInputStream bais = null;
        ByteArrayOutputStream baos = null;
        try {
            bais = new BufferedInputStream(new FileInputStream(f));
            baos = new ByteArrayOutputStream();
            int len;
            while ((len = bais.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (bais != null) {
                bais.close();
            }
        }

        return baos.toByteArray();
    }
}

Related

  1. writeBytes(byte[] bytes, String file)
  2. writeBytes(byte[] data, File file)
  3. writeBytes(File aFile, byte theBytes[])
  4. writeBytes(File dest, byte[] data, int off, int len, boolean append)
  5. writeBytes(File f, byte[] b)
  6. writeBytes(File file, byte[] arr)
  7. writeBytes(File file, byte[] ba)
  8. writeBytes(File file, byte[] bytes)
  9. writeBytes(File file, byte[] bytes)