Java FileOutputStream Write saveBytes(String filename, byte[] data)

Here you can find the source of saveBytes(String filename, byte[] data)

Description

( begin auto-generated from saveBytes.xml ) Opposite of loadBytes(), will write an entire array of bytes to a file.

License

Open Source License

Parameter

Parameter Description
filename name of the file to write to
data array of bytes to be written

Declaration

public static void saveBytes(String filename, byte[] data) 

Method Source Code

//package com.java2s;
/*// w  w  w.j a va  2 s  . c o m
Part of the Processing project - http://processing.org
    
Copyright (c) 2012-13 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
    
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
    
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
    
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA  02111-1307  USA
*/

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.OutputStream;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**
     * ( begin auto-generated from saveBytes.xml )
     *
     * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a
     * file. The data is saved in binary format. This file is saved to the
     * sketch's folder, which is opened by selecting "Show sketch folder" from
     * the "Sketch" menu.<br />
     * <br />
     * It is not possible to use saveXxxxx() functions inside a web browser
     * unless the sketch is <a
     * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
     * save a file back to a server, see the <a
     * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
     * web</A> code snippet on the Processing Wiki.
     *
     * ( end auto-generated )
     *
     * @webref output:files
     * @param filename name of the file to write to
     * @param data array of bytes to be written
     * @see PApplet#loadStrings(String)
     * @see PApplet#loadBytes(String)
     * @see PApplet#saveStrings(String, String[])
     */
    public static void saveBytes(String filename, byte[] data) {
        saveBytes(saveFile(filename), data);
    }

    /**
     * @nowebref
     * Saves bytes to a specific File location specified by the user.
     */
    static public void saveBytes(File file, byte[] data) {
        File tempFile = null;
        try {
            File parentDir = file.getParentFile();
            tempFile = File.createTempFile(file.getName(), null, parentDir);

            OutputStream output = createOutput(tempFile);
            saveBytes(output, data);
            output.close();
            output = null;

            if (file.exists()) {
                if (!file.delete()) {
                    System.err.println("Could not replace " + file.getAbsolutePath());
                }
            }

            if (!tempFile.renameTo(file)) {
                System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath());
            }

        } catch (IOException e) {
            System.err.println("error saving bytes to " + file);
            if (tempFile != null) {
                tempFile.delete();
            }
            e.printStackTrace();
        }
    }

    /**
     * @nowebref
     * Spews a buffer of bytes to an OutputStream.
     */
    static public void saveBytes(OutputStream output, byte[] data) {
        try {
            output.write(data);
            output.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Identical to savePath(), but returns a File object.
     */
    public static File saveFile(String where) {
        return new File(savePath(where));
    }

    /**
     * ( begin auto-generated from createOutput.xml )
     *
     * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b>
     * for a given filename or path. The file will be created in the sketch
     * folder, or in the same folder as an exported application.
     * <br /><br />
     * If the path does not exist, intermediate folders will be created. If an
     * exception occurs, it will be printed to the console, and <b>null</b>
     * will be returned.
     * <br /><br />
     * This function is a convenience over the Java approach that requires you
     * to 1) create a FileOutputStream object, 2) determine the exact file
     * location, and 3) handle exceptions. Exceptions are handled internally by
     * the function, which is more appropriate for "sketch" projects.
     * <br /><br />
     * If the output filename ends with <b>.gz</b>, the output will be
     * automatically GZIP compressed as it is written.
     *
     * ( end auto-generated )
     * @webref output:files
     * @param filename name of the file to open
     * @see PApplet#createInput(String)
     * @see PApplet#selectOutput()
     */
    public OutputStream createOutput(String filename) {
        return createOutput(saveFile(filename));
    }

    /**
     * @nowebref
     */
    static public OutputStream createOutput(File file) {
        try {
            createPath(file); // make sure the path exists
            FileOutputStream fos = new FileOutputStream(file);
            if (file.getName().toLowerCase().endsWith(".gz")) {
                return new GZIPOutputStream(fos);
            }
            return fos;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Returns a path inside the applet folder to save to. Like sketchPath(),
     * but creates any in-between folders so that things save properly.
     * <p/>
     * All saveXxxx() functions use the path to the sketch folder, rather than
     * its data folder. Once exported, the data folder will be found inside the
     * jar file of the exported application or applet. In this case, it's not
     * possible to save data into the jar file, because it will often be running
     * from a server, or marked in-use if running from a local file system.
     * With this in mind, saving to the data path doesn't make sense anyway.
     * If you know you're running locally, and want to save to the data folder,
     * use <TT>saveXxxx("data/blah.dat")</TT>.
     */
    public static String savePath(String where) {
        if (where == null)
            return null;
        createPath(where);
        return where;
    }

    /**
     * Takes a path and creates any in-between folders if they don't
     * already exist. Useful when trying to save to a subfolder that
     * may not actually exist.
     */
    static public void createPath(String path) {
        createPath(new File(path));
    }

    static public void createPath(File file) {
        try {
            String parent = file.getParent();
            if (parent != null) {
                File unit = new File(parent);
                if (!unit.exists())
                    unit.mkdirs();
            }
        } catch (SecurityException se) {
            System.err.println("You don't have permissions to create " + file.getAbsolutePath());
        }
    }
}

Related

  1. saveBytes(File f, byte[] content)
  2. saveBytes(File file, byte[] bytes)
  3. saveBytes(String filename, byte[] byteData)
  4. saveBytes(String filename, byte[] bytes)
  5. saveBytes(String filename, byte[] data)
  6. saveBytesToFile(byte[] bytes, File file)
  7. saveBytesToFile(byte[] bytes, File file)
  8. saveBytesToFile(byte[] data, File file)
  9. saveBytesToFile(byte[] str, File file)