Java File Read by Charset setFileText(File file, Charset charset, String text)

Here you can find the source of setFileText(File file, Charset charset, String text)

Description

Writes a string to a text file, using the specified encoding.

License

Open Source License

Parameter

Parameter Description
file the file to write.
charset the character set to use for the encoding of the file.
text the string to write into the file.

Return

true if the operation succeeded completely; false otherwise.

Declaration

public static boolean setFileText(File file, Charset charset, String text) 

Method Source Code

//package com.java2s;
/*---------------------------------------------------------------
*  Copyright 2005 by the Radiological Society of North America
*
*  This source software is released under the terms of the
*  RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/

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

import java.io.FileOutputStream;

import java.io.OutputStreamWriter;

import java.nio.charset.Charset;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    /**//w ww  . ja v  a 2 s.  co  m
     * Writes a string to a text file, trying to determine the desired encoding
     * from the text itself and using the UTF-8 encoding as a default.
     * @param file the file to write.
     * @param text the string to write into the file.
     * @return true if the operation succeeded completely; false otherwise.
     */
    public static boolean setFileText(File file, String text) {
        Charset charset = getEncoding(text);
        return setFileText(file, charset, text);
    }

    /**
     * Writes a string to a text file, using the specified encoding, or
     * UTF-8 if the specified encoding is not supported.
     * @param file the file to write.
     * @param encoding the name of the charset to use.
     * @param text the string to write into the file.
     * @return true if the operation succeeded completely; false otherwise.
     */
    public static boolean setFileText(File file, String encoding, String text) {
        Charset charset;
        try {
            charset = Charset.forName(encoding);
        } catch (Exception ex) {
            charset = utf8;
        }
        return setFileText(file, charset, text);
    }

    /**
     * Writes a string to a text file, using the specified encoding.
     * @param file the file to write.
     * @param charset the character set to use for the encoding of the file.
     * @param text the string to write into the file.
     * @return true if the operation succeeded completely; false otherwise.
     */
    public static boolean setFileText(File file, Charset charset, String text) {
        BufferedWriter bw = null;
        boolean result = true;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
            bw.write(text, 0, text.length());
        } catch (Exception e) {
            result = false;
        } finally {
            try {
                bw.flush();
                bw.close();
            } catch (Exception ignore) {
            }
        }
        return result;
    }

    private static Charset getEncoding(String text) {

        //See if this is an xml document with an encoding declaration.
        Pattern xml = Pattern.compile("^\\s*<\\?xml\\s+[^>]*\\s*encoding\\s*=\\s*(\"[^\"]*\")",
                Pattern.DOTALL | Pattern.MULTILINE);
        Matcher xmlMatcher = xml.matcher(text);
        if (xmlMatcher.find())
            return getEncoding(xmlMatcher);

        //See if this is an html document with a charset declaration.
        Pattern html = Pattern.compile(
                "^\\s*<(html|HTML).*<(meta|META)\\s+[^>]*\\s*(charset|CHARSET)\\s*=\\s*(\"[^\"]*\"|[^\"\\s]*)",
                Pattern.DOTALL | Pattern.MULTILINE);
        Matcher htmlMatcher = html.matcher(text);
        if (htmlMatcher.find())
            return getEncoding(htmlMatcher);

        //We don't recognize this document declaration; use UTF-8.
        //Maybe this should actually be ISO-8859-1 since
        //that is the web default encoding, but it is probably
        //better to default to UTF-8 because that will be better
        //for sites in the Far East, and the pain for the Europeans
        //will be minimal.
        return utf8;
    }

    private static Charset getEncoding(Matcher matcher) {
        int groups = matcher.groupCount();
        String name = matcher.group(groups);
        if (name.startsWith("\""))
            name = name.substring(1);
        if (name.endsWith("\""))
            name = name.substring(0, name.length() - 1);
        try {
            return Charset.forName(name);
        } catch (Exception ex) {
            return utf8;
        }
    }
}

Related

  1. loadString(File f, Charset charset)
  2. open(File file, Charset charset)
  3. parseNameDelimiterValueNewLineFile( File nameDelimiterValueNewLineFile, String nameValueDelimiter, Charset charset)
  4. saveFile(File file, String content, String charsetName)
  5. saveToFile(File dest, String contents, Charset cs)
  6. setPropertiesVaule(File file, String key, String value, String comments, Charset charset)
  7. setText(File file, Charset charset, String text)
  8. stringToFile(final String s, final File f, final Charset c)
  9. stringToFile(final String string, final Path path, final Charset charset)