All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dorkbox.inputConsole.Encoding Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2002-2012, the original author or authors.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *
 * http://www.opensource.org/licenses/bsd-license.php
 *
 * @author Jason Dillon
 * @author Guillaume Nodet
 */
package dorkbox.inputConsole;

import java.nio.charset.Charset;

public class Encoding {

    /**
     * Get the default encoding. Will first look at the LC_CTYPE environment variable, then the input.encoding system property, then the
     * default charset according to the JVM.
     *
     * @return The default encoding to use when none is specified.
     */
    public static String get() {
        // LC_CTYPE is usually in the form en_US.UTF-8
        String envEncoding = extractEncodingFromCtype(System.getenv("LC_CTYPE"));
        if (envEncoding != null) {
            return envEncoding;
        }
        return System.getProperty("input.encoding", Charset.defaultCharset().name());
    }

    /**
     * Parses the LC_CTYPE value to extract the encoding according to the POSIX standard, which says that the LC_CTYPE environment variable
     * may be of the format [language[_territory][.codeset][@modifier]]
     *
     * @param ctype The ctype to parse, may be null
     * @return The encoding, if one was present, otherwise null
     */
    private static String extractEncodingFromCtype(String ctype) {
        if (ctype != null && ctype.indexOf('.') > 0) {
            String encodingAndModifier = ctype.substring(ctype.indexOf('.') + 1);
            if (encodingAndModifier.indexOf('@') > 0) {
                return encodingAndModifier.substring(0, encodingAndModifier.indexOf('@'));
            }
            return encodingAndModifier;
        }
        return null;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy