Java Text File Save writeFile(String string, File file)

Here you can find the source of writeFile(String string, File file)

Description

Writes the string specified to the file specified.

License

Open Source License

Parameter

Parameter Description
string A string to write
file The file to write <code>string</code> to

Declaration

public static void writeFile(String string, File file) 

Method Source Code

//package com.java2s;
/**//www.j av  a2  s  . c  om
 * A class of utilities related to strings. Originally written by Alexander Boyd
 * for the OpenGroove project (www.opengroove.org). Released under the terms of
 * the GNU Lesser General Public License.
 * 
 * @author Alexander Boyd
 * 
 */

import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**
     * Writes the string specified to the file specified.
     * 
     * @param string
     *            A string to write
     * @param file
     *            The file to write <code>string</code> to
     */
    public static void writeFile(String string, File file) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(string.getBytes("UTF-8"));
            FileOutputStream fos = new FileOutputStream(file);
            copy(bais, fos);
            bais.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Copies the contents of one stream to another. Bytes from the source
     * stream are read until it is empty, and written to the destination stream.
     * Neither the source nor the destination streams are flushed or closed.
     * 
     * @param in
     *            The source stream
     * @param out
     *            The destination stream
     * @throws IOException
     *             if an I/O error occurs
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[8192];
        int amount;
        while ((amount = in.read(buffer)) != -1) {
            out.write(buffer, 0, amount);
        }
    }
}

Related

  1. WriteFile(String sFileName, String content)
  2. writeFile(String sFileName, String sContent)
  3. writeFile(String sName, String data, String encoding)
  4. writeFile(String str, File f)
  5. writeFile(String str, String filename, boolean append)
  6. writeFile(String string, File location, boolean forceASCII)
  7. writeFile(String tailored, File f)
  8. writeFile(String targetPath, String filename, byte[] content)
  9. writeFile(String text, File file, boolean append)