Java Text File Write by Charset write(File file, Charset charset, String content)

Here you can find the source of write(File file, Charset charset, String content)

Description

write

License

Apache License

Declaration

public static void write(File file, Charset charset, String content) 

Method Source Code

//package com.java2s;
/**// w  w w.  ja  va2 s.com
 * Copyright 2016 Pascal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

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

import java.io.OutputStreamWriter;

import java.io.Writer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    private static final Charset CHARSET = StandardCharsets.UTF_8;

    public static void write(File file, String content) {
        write(file, CHARSET, content);
    }

    public static void write(File file, Charset charset, String content) {
        try (Writer writer = createWriter(file, charset)) {
            writer.write(content);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    public static Writer createWriter(File file) throws FileNotFoundException {
        return createWriter(file, CHARSET);
    }

    public static Writer createWriter(File file, Charset charset) throws FileNotFoundException {
        return new OutputStreamWriter(new FileOutputStream(file), charset);
    }
}

Related

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