Java Text File Write by Charset write(File file, Object content, Charset cs, boolean append)

Here you can find the source of write(File file, Object content, Charset cs, boolean append)

Description

Writes string content into a file.

License

Open Source License

Parameter

Parameter Description
file > the file to be opened for writing
content > the content to be written
cs > default UTF-8
append if true, the content will be written to the end of the file rather than the beginning

Declaration

public static boolean write(File file, Object content, Charset cs, boolean append) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;

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

import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class Main {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public static boolean write(File file, Object content) {
        return write(file, content, UTF8, true);
    }/* ww w  . ja  v a  2  s .  co  m*/

    public static boolean write(File file, Object content, boolean append) {
        return write(file, content, UTF8, append);
    }

    public static boolean write(File file, Object content, Charset cs, boolean append) {
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream(file, append), cs);
            bw = new BufferedWriter(osw);
            bw.write(content.toString());
            bw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeStreams(bw, osw);
        }
        return true;
    }

    public static void closeStreams(Closeable... streams) {
        try {
            for (Closeable stream : streams) {
                if (stream != null) {
                    stream.close();
                }
            }
        } catch (IOException e) {
            System.out.println("Close IO stream failure.");
            e.printStackTrace();
        }
    }
}

Related

  1. newWriter(WritableByteChannel ch, Charset cs)
  2. openTextFileForWriting(File f, Charset encoding)
  3. openWriter(OutputStream stream, Charset charset, boolean autoflush)
  4. write(char[] data, File file, String charsetName)
  5. write(File file, Charset charset, String content)
  6. write(final String s, final OutputStream out, Charset charset)
  7. write(Path file, CharBuffer data, Charset cs)
  8. write(Path path, Iterable lines, Charset cs, OpenOption... options)
  9. write(Path path, Iterable lines, Charset cs, OpenOption... options)