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

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

Description

Write a file to disk

Parameter

Parameter Description
path file's path
fileName file's name
datas file's data
overwrite if overwrite existing file

Return

file has been write

Declaration

public static File writeFile(String path, 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 {
    /**//from   w  w w .  ja  v  a  2  s  .  c o m
     * 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. saveFile(byte[] data, String fileName)
  2. writeBytes(File file, boolean append, byte[] bytes)
  3. writeBytes(byte[] bytes, File file, boolean append)
  4. writeFile(String fileName, byte[] content)
  5. writeFile(String fileName, byte[] datas, boolean overwrite)
  6. saveBytes(byte[] bytes, File file)
  7. saveBytes(byte[] bytes, OutputStream out)
  8. saveBytes(byte[] bytes, String file)
  9. writeByteArrayToSD(String path, byte[] content, boolean create)