Java File Read by Charset saveFile(File file, String content, String charsetName)

Here you can find the source of saveFile(File file, String content, String charsetName)

Description

save File

License

Open Source License

Declaration

public static void saveFile(File file, String content, String charsetName) 

Method Source Code


//package com.java2s;
import java.io.Closeable;
import java.io.File;

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

import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import java.nio.charset.CharsetEncoder;

public class Main {
    public static void saveFile(File file, String content, String charsetName) {
        // if (Utils.isEmpty(fileName) || Utils.isEmpty(content)) {
        // return;
        // }/*ww  w  . ja  v  a 2  s .  c o m*/
        // logger.info("save file:" + fileName + " charset:" + charsetName);
        file.getParentFile().mkdirs();
        Charset cs;
        if (null == charsetName || "".equals(charsetName)) {
            cs = Charset.defaultCharset();
        } else {
            cs = Charset.forName(charsetName);
        }
        CharsetEncoder encoder = cs.newEncoder();
        FileOutputStream os = null;
        FileChannel out = null;
        try {
            os = new FileOutputStream(file);
            out = os.getChannel();
            out.write(encoder.encode(CharBuffer.wrap(content)));
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(out);
            close(os);
        }
    }

    public static void close(Closeable c) {
        if (null != c) {
            try {
                c.close();
                c = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. loadFile(File file, Charset cs)
  2. loadFile(File logfile, Charset charset)
  3. loadString(File f, Charset charset)
  4. open(File file, Charset charset)
  5. parseNameDelimiterValueNewLineFile( File nameDelimiterValueNewLineFile, String nameValueDelimiter, Charset charset)
  6. saveToFile(File dest, String contents, Charset cs)
  7. setFileText(File file, Charset charset, String text)
  8. setPropertiesVaule(File file, String key, String value, String comments, Charset charset)
  9. setText(File file, Charset charset, String text)