Here you can find the source of writeBytesSafely(File aFile, byte theBytes[])
public static void writeBytesSafely(File aFile, byte theBytes[]) throws IOException
//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; } }