Java PrintWriter Write saveStrings(String filename, String data[])

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

Description

( begin auto-generated from saveStrings.xml ) Writes an array of strings to a file, one line per string.

License

Open Source License

Parameter

Parameter Description
filename filename for output
data string array to be written

Declaration

public static void saveStrings(String filename, String data[]) 

Method Source Code

//package com.java2s;
/*//from   w  w w .  ja v  a 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.BufferedOutputStream;

import java.io.File;

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

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**
     * ( begin auto-generated from saveStrings.xml )
     *
     * Writes an array of strings to a file, one line per string. 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.<br/>
     * <br/ >
     * Starting with Processing 1.0, all files loaded and saved by the
     * Processing API use UTF-8 encoding. In previous releases, the default
     * encoding for your platform was used, which causes problems when files
     * are moved to other platforms.
     *
     * ( end auto-generated )
     * @webref output:files
     * @param filename filename for output
     * @param data string array to be written
     * @see PApplet#loadStrings(String)
     * @see PApplet#loadBytes(String)
     * @see PApplet#saveBytes(String, byte[])
     */
    public static void saveStrings(String filename, String data[]) {
        saveStrings(saveFile(filename), data);
    }

    /**
     * @nowebref
     */
    static public void saveStrings(File file, String data[]) {
        saveStrings(createOutput(file), data);
    }

    /**
     * @nowebref
     */
    static public void saveStrings(OutputStream output, String[] data) {
        PrintWriter writer = createWriter(output);
        for (int i = 0; i < data.length; i++) {
            writer.println(data[i]);
        }
        writer.flush();
        writer.close();
    }

    /**
     * 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;
    }

    /**
     * ( begin auto-generated from createWriter.xml )
     *
     * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object
     * to write to it. For the file to be made correctly, it should be flushed
     * and must be closed with its <b>flush()</b> and <b>close()</b> methods
     * (see above example).
     * <br/> <br/>
     * Starting with Processing release 0134, all files loaded and saved by the
     * Processing API use UTF-8 encoding. In previous releases, the default
     * encoding for your platform was used, which causes problems when files
     * are moved to other platforms.
     *
     * ( end auto-generated )
     *
     * @webref output:files
     * @param filename name of the file to be created
     * @see PrintWriter
     * @see PApplet#createReader
     * @see BufferedReader
     */
    public PrintWriter createWriter(String filename) {
        return createWriter(saveFile(filename));
    }

    /**
     * @nowebref
     * I want to print lines to a file. I have RSI from typing these
     * eight lines of code so many times.
     */
    static public PrintWriter createWriter(File file) {
        try {
            createPath(file); // make sure in-between folders exist
            OutputStream output = new FileOutputStream(file);
            if (file.getName().toLowerCase().endsWith(".gz")) {
                output = new GZIPOutputStream(output);
            }
            return createWriter(output);

        } catch (Exception e) {
            if (file == null) {
                throw new RuntimeException("File passed to createWriter() was null");
            } else {
                e.printStackTrace();
                throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath());
            }
        }
        //return null;
    }

    /**
     * @nowebref
     * I want to print lines to a file. Why am I always explaining myself?
     * It's the JavaSoft API engineers who need to explain themselves.
     */
    static public PrintWriter createWriter(OutputStream output) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(output, 8192);
            OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");
            return new PrintWriter(osw);
        } catch (UnsupportedEncodingException e) {
        } // not gonna happen
        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. saveSortedMap(Map map, File mapFile, String separator, String qualifier, String encoding)
  2. saveString(String theFilePath, String theString)
  3. saveStringAsFile(String string, String path)
  4. saveStringBufferTofile(String fileName, StringBuffer sb)
  5. saveStrings(final String filename, final String[] sArray)
  6. saveStrings(String theFilePath, String[] theStrings)
  7. saveStringToFile(String text, String path)
  8. saveToFile(String buf, String fileName)
  9. saveToFile(String path, String data)