Android Byte Array Save to File writeFile(String fileName, byte[] datas, boolean overwrite)

Here you can find the source of writeFile(String fileName, byte[] datas, boolean overwrite)

Description

write File

Declaration

public static File writeFile(String fileName, byte[] datas,
            boolean overwrite) throws IOException, FileNotFoundException 

Method Source Code

//package com.java2s;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;

public class Main {
    /**/*w ww .java  2s. c  om*/
     * Write a file to disk
     * @param path file's path
     * @param fileName file's name
     * @param datas file's data
     * @param overwrite if overwrite existing file
     * @return file has been write
     */
    public static File writeFile(String path, String fileName,
            byte[] datas, boolean overwrite) throws IOException,
            FileNotFoundException {
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }
        file = new File(path + fileName);
        if (file.exists()) {
            if (!overwrite) {
                fileName = Math.random() + fileName;
                file = new File(path + fileName);
            } else {
                file.delete();
            }
        }

        file.createNewFile();

        FileOutputStream fos = new FileOutputStream(path + fileName);
        fos.write(datas);
        fos.close();

        return file;
    }

    public static File writeFile(String fileName, byte[] datas,
            boolean overwrite) throws IOException, FileNotFoundException {
        File file = new File(fileName);
        if (file.exists()) {
            if (!overwrite) {
                fileName = Math.random() + fileName;
                file = new File(fileName);
            } else {
                file.delete();
            }
        }

        file.createNewFile();

        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(datas);
        fos.close();

        return file;
    }
}

Related

  1. saveBytes(@NotNull File file, @NotNull byte[] bytes)
  2. saveFile(byte[] data, String fileName)
  3. writeBytes(File file, boolean append, byte[] bytes)
  4. writeBytes(byte[] bytes, File file, boolean append)
  5. writeFile(String fileName, byte[] content)
  6. writeFile(String path, String fileName, byte[] datas, boolean overwrite)
  7. saveBytes(byte[] bytes, File file)
  8. saveBytes(byte[] bytes, OutputStream out)
  9. saveBytes(byte[] bytes, String file)