Java FileOutputStream Write Byte Array writeBytesSafely(File aFile, byte theBytes[])

Here you can find the source of writeBytesSafely(File aFile, byte theBytes[])

Description

Writes the given bytes (within the specified range) to the given file, with an option for doing it "safely".

License

Open Source License

Declaration

public static void writeBytesSafely(File aFile, byte theBytes[]) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

public class Main {
    /**//from  w  w  w  .java2  s .c om
     * Writes the given bytes (within the specified range) to the given file, with an option for doing it "safely".
     */
    public static void writeBytesSafely(File aFile, byte theBytes[]) throws IOException {
        if (theBytes == null) {
            aFile.delete();
            return;
        }
        if (!aFile.exists()) {
            writeBytes(aFile, theBytes);
            return;
        }
        File bfile = new File(aFile.getPath() + ".rmbak");
        copyFile(aFile, bfile);
        writeBytes(aFile, theBytes);
        bfile.delete();
    }

    /**
     * Writes the given bytes (within the specified range) to the given file.
     */
    public static void writeBytes(File aFile, byte theBytes[]) throws IOException {
        if (theBytes == null) {
            aFile.delete();
            return;
        }
        FileOutputStream fileStream = new FileOutputStream(aFile);
        fileStream.write(theBytes);
        fileStream.close();
    }

    /**
     * Returns the path for a file.
     */
    public static String getPath(File aFile) {
        return aFile.getAbsolutePath();
    }

    /**
     * Copies a file from one location to another.
     */
    public static File copyFile(File aSource, File aDest) throws IOException {
        // Get input stream, output file and output stream
        FileInputStream fis = new FileInputStream(aSource);
        File out = aDest.isDirectory() ? new File(aDest, aSource.getName()) : aDest;
        FileOutputStream fos = new FileOutputStream(out);

        // Iterate over read/write until all bytes written
        byte[] buf = new byte[8192];
        for (int i = fis.read(buf); i != -1; i = fis.read(buf))
            fos.write(buf, 0, i);

        // Close in/out streams and return out file
        fis.close();
        fos.close();
        return out;
    }
}

Related

  1. writeBytes(int[] data, String filename)
  2. writeBytes(String filename, byte[] bytes)
  3. writeBytes(String filename, byte[] data, int len)
  4. writeBytes(String filePath, boolean append, byte[] content)
  5. writeBytesInFile(File f, String data)
  6. writeBytesToFile(byte[] bfile, String filePath, String fileName)
  7. writeBytesToFile(byte[] byteContent, String fileName)
  8. writeBytesToFile(byte[] bytes, File file)
  9. writeBytestoFile(byte[] bytes, String filepath)