Java UTF8 isSystemUtf8()

Here you can find the source of isSystemUtf8()

Description

is System Utf

License

Open Source License

Return

true if system uses UTF-8 by default

Declaration

public static boolean isSystemUtf8() 

Method Source Code


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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class Main {
    /** Cached copy of system encoding string */
    private static String _systemEncoding = null;

    /**//from   www  .j  a v a  2  s.  c o m
     * @return true if system uses UTF-8 by default
     */
    public static boolean isSystemUtf8() {
        String systemEncoding = getSystemEncoding();
        return (systemEncoding != null && systemEncoding.toUpperCase().equals("UTF-8"));
    }

    /**
     * @return name of the system's character encoding
     */
    public static String getSystemEncoding() {
        if (_systemEncoding == null) {
            _systemEncoding = determineSystemEncoding();
        }
        return _systemEncoding;
    }

    /**
     * Use a temporary file to obtain the name of the default system encoding
     * @return name of default system encoding, or null if write failed
     */
    private static String determineSystemEncoding() {
        File tempFile = null;
        String encoding = null;
        try {
            tempFile = File.createTempFile("gpsprune", null);
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tempFile));
            encoding = getEncoding(writer);
            writer.close();
        } catch (IOException e) {
        } // value stays null
          // Delete temp file
        if (tempFile != null && tempFile.exists()) {
            if (!tempFile.delete()) {
                System.err.println("Cannot delete temp file: " + tempFile.getAbsolutePath());
            }
        }
        // If writing failed (eg permissions) then just ask system for default
        if (encoding == null)
            encoding = Charset.defaultCharset().name();
        return encoding;
    }

    /**
     * Get the default system encoding using a writer
     * @param inWriter writer object
     * @return string defining encoding
     */
    public static String getEncoding(OutputStreamWriter inWriter) {
        String encoding = inWriter.getEncoding();
        try {
            encoding = Charset.forName(encoding).name();
        } catch (Exception e) {
        } // ignore failure to find encoding
        return encoding;
    }
}

Related

  1. getUtf8String(URL url)
  2. getUTF8SuportOutput()
  3. getUTF8Writer(String path)
  4. hasLeadingWhitespace(File inputFile)
  5. inputStreamToFile(final InputStream inputStream, final File outputFile)
  6. isUtf8Supported()
  7. loadStringUTF8(InputStream in)
  8. makeUTF8()
  9. moveFile(File inFile, File outFile)